Java reflection to get private public properties and methods
Recently in the Java based on a certain review before the reflection of a period of time will be in the brain gradually lost, so take advantage of this free time to quickly restore the knowledge point, first to a simple example of it. Save it all at once. 1. First, we'll create some attributes and methods for the reflected class.
public class Student {
//private Property private
String name;
Private method Private
void Say (String s) {
log.d ("QQ", "I am" + s+ "ah");
}
Common property public
int age;
Common method public
void Luru (String name) {
LOG.D ("QQ", "I am" + name);
}
2. We're going to implement the call to this example.
public class Mainactivity extends appcompatactivity {@Override protected void onCreate (Bundle savedinstancestate
) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Using reflection to get the private property private method of a class object Student s = new Student ();
try {//Get Class object class CLS = Class.forName (S.getclass (). GetName ());
Generate Instance Object o = Cls.newinstance ();
Gets the private property Field name = Cls.getdeclaredfield ("name");
Name.setaccessible (TRUE);
Name.set (o, "I am a private property");
LOG.D ("QQ", "I set the name:" + name.get (o));
Gets private Methods method say = Cls.getdeclaredmethod ("Say", New Class[]{string.class});
Say.setaccessible (TRUE);
Say.invoke (O, "private Method");
Gets the public property Field age = Cls.getfield (' age ');
Age.setaccessible (TRUE);
Age.set (o,11); LOG.D ("QQ", "I set the Age:" + age.geT (o));
Get public Methods Method Luru = Cls.getmethod ("Luru", New Class[]{string.class});
Luru.setaccessible (TRUE);
Luru.invoke (O, "public method");
catch (Exception e) {e.printstacktrace (); }
}
}The above is the content of this period, thank you for watching ...