Java reflection mechanism is in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties
Import Java.lang.reflect.Field;
Import java.lang.reflect.InvocationTargetException;
Import Java.lang.reflect.Method;
public class Fanshe {
public static void Main (string[] args) {
try {
Class C = Class.forName ("User");//Get Class
Object o = c.newinstance ();//Instantiate this class to assign O
Field id = c.getdeclaredfield ("id");//Get id attribute
Id.setaccessible (TRUE);//Break Package
Id.set (o, 111);//Assign value to O Object ID property
System.out.println ("id=====" +id.get (o));//get results
Class cls[] = new CLASS[2];
Cls[0] = Int.class;
CLS[1] = Int.class;
Method method2 = C.getdeclaredmethod ("SetId", CLS);//methods name and parameter type
Method method = C.getdeclaredmethod ("SetId", int.class,int.class);//methods name and parameter type
System.out.println ("Method = = =" +method);
Method.setaccessible (TRUE);
Method.invoke (o, 100,101);//invoke gets the return value of the specified method
Method method1 = C.getdeclaredmethod ("getId", null);//Methods without parameters
Method1.setaccessible (TRUE);
System.out.println ("= = =" +method1.invoke (o));
} catch (ClassNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (Instantiationexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (Illegalaccessexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (Nosuchfieldexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (SecurityException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (Nosuchmethodexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (IllegalArgumentException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (InvocationTargetException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
Class user{
private int id;
private String name;
private int getId () {
return ID;
}
private void setId (int id,int name) {
System.out.println ("It's a nice Day" +id+name);
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
}
Note: After getting the object, to setaccessible break the package
Java Reflection mechanism