The Java Reflection mechanism provides the following functions: To determine the class to which any object belongs at run time, to construct an object of any class at run time, to determine the member variables and methods that any class has at run time , and to invoke methods of any object at run time.
Public classJavatest { Public Static voidMain (string[] args) {Try{Class MyClass= Class.forName ("Student"); Object Student=(Object) myclass.newinstance (); Method Method= Myclass.getmethod ("Printstudent", String.class, String.class); Method.invoke (student,"Zhangsan", "the"); } Catch(Exception e) {e.printstacktrace (); } System.out.println ("End"); }}classstudent{ Public voidPrintstudent (FinalString ID,FinalString name) {System.out.println ("id =" + id + ", name =" +name); }}
Invoke (Object obj, Object ... args) throws Illegalaccessexception, illegalargumentexception, invocationtargetexception
-
Called on the specified object with the specified argument.
Method
The underlying method that the object represents. Individual parameters are automatically unpacked to match the basic parameters, and both the basic and reference parameters are subject to the method invocation transformation.
If the underlying method is static, the specified argument can be ignored obj
. The parameter can be null.
If the underlying method requires a shape parameter of 0, the supplied args
array can be 0 or null in length.
-
Parameters:
-
obj
-Object from which the underlying method is invoked
-
args
-parameters for method invocation
-
Return:
-
Use parameters
args
to
obj
Assign the result of the method represented on the object
-
Thrown:
-
IllegalAccessException
-If this
Method
object enforces Java language access control, and the underlying method is inaccessible.
-
IllegalArgumentException
-If the method is an instance method, and the specified object parameter is not an instance of the class or interface (or the subclasses or the implementation program) that declares the underlying method, if the number of arguments and parameters is not the same, if the package conversion of the base parameter fails; You cannot convert a parameter value to the corresponding formal parameter type through a method call transformation.
-
InvocationTargetException
-if the underlying method throws an exception.
-
NullPointerException
-If the specified object is null, and the method is an instance method.
-
ExceptionInInitializerError
-If the initialization caused by this method fails.
Java Learning (i): A simple example of reflection