T
- The class type that has the method to be invoked.R
- The expected return type of the method invocation.public class ReflectionMethodInvoker<T,R> extends Object
The relatively expensive call to find the correct method on the class is lazy and will not be performed until the first invocation or until the invoker is explicitly initialized. Once found, the method is cached so repeated calls to initialize() or invoke() will not incur the reflection cost of searching for the method on the class.
Example:
ReflectionMethodInvoker<String, Integer> invoker =
new ReflectionMethodInvoker<String, Integer>(String.class, Integer.class, "indexOf", String.class, int.class);
invoker.invoke("ababab", "ab", 1); // This is equivalent to calling "ababab".indexOf("ab", 1);
Constructor and Description |
---|
ReflectionMethodInvoker(Class<? extends T> clazz,
Class<R> returnType,
String methodName,
Class<?>... parameterTypes)
Construct an instance of
ReflectionMethodInvoker . |
Modifier and Type | Method and Description |
---|---|
void |
initialize()
Initializes the method invoker by finding and caching the target method from the target class that will be used
for subsequent invoke operations.
|
R |
invoke(T obj,
Object... args)
Attempt to invoke the method this proxy targets for on the given object with the given arguments.
|
boolean |
isInitialized()
Gets the initialization state of the invoker.
|
public ReflectionMethodInvoker(Class<? extends T> clazz, Class<R> returnType, String methodName, Class<?>... parameterTypes)
ReflectionMethodInvoker
.
This constructor will not make any reflection calls as part of initialization; i.e. no validation of the existence of the given method signature will occur.
clazz
- The class that has the method to be invoked.returnType
- The expected return class of the method invocation. The object returned by the invocation
will be cast to this class.methodName
- The name of the method to invoke.parameterTypes
- The classes of the parameters of the method to invoke.public R invoke(T obj, Object... args) throws NoSuchMethodException
obj
- The object to invoke the method on.args
- The arguments to pass to the method. These arguments must match the signature of the method.NoSuchMethodException
- if the JVM could not find a method matching the signature specified in the
initialization of this proxy.SdkClientException
- if any other exception is thrown when attempting to invoke the method or by the
method itself. The cause of this exception will be the exception that was actually thrown.public void initialize() throws NoSuchMethodException
NoSuchMethodException
- if the JVM could not find a method matching the signature specified in the
initialization of this proxy.public boolean isInitialized()
Copyright © 2023. All rights reserved.