Common Java reflection API summary

JAVA reflection mechanism is in the operating state, for any class, are made known to all properties and methods of this class; for any object, are able to call any of its methods and properties; This dynamic access to information and dynamic method call object the feature is called reflection java language.
JAVA reflection (radiation) mechanism: "the program is run, the program structure allows changing or variable type, such language is called dynamic language." From this point of view, Perl, Python, Ruby is a dynamic language, C ++, Java, C # is not dynamic languages. But JAVA has a very prominent dynamic mechanisms: Reflection, Java is used in the body means that we can run at load time, Discovery, using completely unknown during compilation classes. In other words, Java programs can be loaded only when a class name to run that, informed its full configuration (but not the methods defined), and generates its object entity, or its fields set value, or arouse their methods.

First, get a class object

1、通过对象获取,obj.getClass();
2、通过类路径名获取,Class.forName("com.metadata.Student");
3、通过类名获取,Object.class;

Second, the common API similarities and differences

getField、getMethod和getCostructor方法可以获得指定名字的域、方法和构造器。
getFields、getMethods和getCostructors方法可以获得类提供的public域、方法和构造器数组,其中包括超类的共有成员。
getDeclatedFields、getDeclatedMethods和getDeclaredConstructors方法可以获得类中声明的全部域、方法和构造器,其中包括私有和受保护的成员,但不包括超类的成员。

Third, the manipulated variable, method, constructor

1、变量
    get
    set
2、方法
    invoke(Object obj, Object... args)
3、构造方法
    Class.newInstance() 只能够调用无参的构造函数,即默认的构造函数; 
    Constructor.newInstance() 可以根据传入的参数,调用任意构造构造函数。

Ignore modifiers
setAccessible (true);

----------------
Disclaimer: This article is the original article CSDN bloggers "Ezioooooo", and follow CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement. .
Original link: https://blog.csdn.net/u012877472/article/details/51084965

Guess you like

Origin www.cnblogs.com/shaoyu/p/11571747.html