Find a method at runtime :
1. Class cls = obj.getClass();
2. Method meth = cls.getMethod ( "methodName", new Class[]{ "ParameterType".class } );
Here, if the "ParameterType" is "Class", then the type of "Parameter" can be represented by ParameterType.class.
".class" literals are Jave's way to specify a class object statically.
Then, what if the "ParameterType" is an array or an interface or a primitive type?
In java, we can also use ".class' literals to represent class objects for an array, interface or primitive.
e.g.
Method meth = Vector.class.getMethod ( "get", new Class[] {int.class} );
Method meth = Vector.class.getMethod( "addAll", new Class[] {Collection.class} );
Method meth = Vector.class.getMethod ( "copyTo", new Class[]{Object[].class});
Understanding Method Objects:
The same as we can use Class object to get the Name of Class(getName()) or get method of Class (getMethod()), we can get method related info from Method object.
e.g. the parameter augments , the return type, the exception type declared to be thrown by this method :
Class[] getExceptionTypes()
Class getReturnType()
Class[] getParameterTypes()
And there is a most important method in Method Class to consist of Reflection API :
invoke(Object obj, Object[] args) : we can invoke one method of the obj object in argument with the args specified in the parameter array args.
e.g.
The Dog Class has a method called " void yell(String words) ", we can invoke it at runtime by following code:
Class cls = Dog.class;
Method meth = cls.getMethod("yell",new Class[]{String.class});
metho.invoke(dog, "wangwangwang"); //here, think "dog" as an instance of Dog Class
Primitive Type as Parameter
If we have to pass a primitive as an argument or return a primitive as an output, we need to wrap it or unwrap it.
e.g.
Method meth = obj.getMethod ("hashCode",null);
int hashcode=(Integer)(meth.invoke(obj,null)).intValue();