Anatomy of the "54" Java reflection mechanism

Source: Internet
Author: User

Java Reflection Mechanism:

1. Refers to classes that can be loaded at run time, detect and use a class that is completely unknown during compilation.

2. In the running state of the program, you can dynamically load a class with only a name, and for any class that has been loaded, you can know all the properties and methods of the class; For any object, any of his methods and properties can be called;

3. After the class has been loaded, a class-type object is produced in heap memory (a class has only a single class object), which contains the structure information of the complete class, and the class object is like a mirror that sees the structure of classes through this mirror, so called: Reflection.

4. After each class is loaded into memory, the system generates a corresponding Java.lang.Class object for that class, which can be accessed through the class object.

The concepts of static load classes and dynamic load classes are differentiated:

The class package that is related to reflection.

java.lang.reflect.*; and Java.lang.Class;

All types in Java (including basic types) correspond to a class object, which is java.lang.Class. That is, each type has a class object in the class that corresponds to it. class has no public constructor method. Note Not no, there is no public.

Get information from class

How to get a class object

1. For each object. GETCALSS (), a corresponding class can be obtained.

2.class.forname (String), string: The name of the package. The name of the package is created. The object that corresponds to the class name

Note: 1.2 Only applies To reference types

3. For the base type: Encapsulation class. The type represents a class object of the corresponding base type. integer.type corresponds to the class object of int
Note: 3 only applies to basic types

4. Type, Class. < 4th is the Universal .>
The above 4 methods, only method 2 is dynamic, just change a package on it. It has the dynamic potential. So the real meaning of the want to embody dynamic programming can only use Method 2.

Each type of class object has only one, that is, their address is only one, but the different types are different. So the following print results are true.
//对与引用类型"".getClass();Class c2 =     Class.forName("java.lang.String");Class c3 = String.class;System.out.println(c1 ==c2);//true//对于基本类型int.class;System.out.println(num1 == num2);//true
Reflection gets the related method of the member in the class [get construct < according to parameter type;] normally used without declared
Constructor<T> getConstructor(Class<?>... parameterTypes)       返回一个 Constructor 对象,它反映此 Class 对象所表示的类的指定公共构造方法。  Constructor<?>[] getConstructors()       返回一个包含某些 Constructor 对象的数组,这些对象反映此 Class 对象所表示的类的所有公共构造方法。  Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)       返回一个 Constructor 对象,该对象反映此 Class 对象所表示的类或接口的指定构造方法。  Constructor<?>[] getDeclaredConstructors()       返回 Constructor 对象的一个数组,这些对象反映此 Class 对象表示的类声明的所有构造方法。
[Get Properties < based on attribute name;] generally used with declared, because properties are generally private
Field getField(String name)       Class 对象所表示的类或接口的指定公共成员字段。  Field[] getFields()       Class 对象所表示的类或接口的所有可访问公共字段。  Field getDeclaredField(String name)       Class 对象所表示的类或接口的指定已声明字段。  Field[] getDeclaredFields()       Class 对象所表示的类或接口所声明的所有字段。
[Get method < method name plus parameter type;] normally used without declared
method GetMethod (String name, class<?>  ...   Parametertypes) Returns a method object that reflects the specified public member methods of the class or interface represented by this class object.   Method[] GetMethods () returns an array containing some method objects that reflect the public member method of the class or interface represented by this class object, including those declared by the class or interface, and those inherited from the superclass and the hyper-interface. Method Getdeclaredmethod (String name, Class<?> parametertypes) returns a Met  A Hod object that reflects the specified declared method of the class or interface represented by this class object.  Method[] Getdeclaredmethods () returns an array of method objects that reflect all methods of the class or interface declaration represented by this class object, including public, protected, default (package) access, and private methods, but not inherited methods. t  newinstance () creates a new instance of the class represented by this class object. <new Instance () can dynamically create objects > String toString () to convert the object to a string. 
Note: The new Instance () call is a parameterless construct, and if the class does not have a parameterless construction method, newinstance () produces an exception. The declared method is to support the private, but does not support inheritance, no declared method supports inheritance, does not support private, And can only take out things that are public. Therefore, when taking the attribute is generally with declared, because the property is generally private, take the method is generally not with declared, When the structure is taken, it is usually not with declared. Example simulation reflection gets the related properties and methods in the class using reflection to assign a value to a property

Methods in field
Object get (Object obj)
Returns the value of the field represented by this field on the specified object.
Field f = C.getxxfield (attribute name);
Value = F.get (object);
void set (Object obj, Object value)
Sets the field that is represented by this field object on the specified object variable to the specified new value.
F.set (object, value);
Class

    Class c = Student.class;    Object obj  = c.newInstance();            //创建Student类的对象    Field f = c.getDeclaredField("name");        //获取name属性    f.setAccessible(true);                    //设置私有可以访问.    f.set"zhangsan");    System.out.println(f.get(obj));             //获取obj的name属性的值.
Construct with reflection calls

For a construct, the real call is when the Newinstance () method is called.

Class C = Class. forname("Com.clazz.reflect.Student");Constructor con = c. GetConstructor(); No execution constructs,Object CObj = C. GetConstructor(). newinstance();//Call an argument-free construction methodConstructor Conall = C. GetConstructor(int. Class, String. ClassInt. Class);Object caobj = Conall. newinstance(1001,"Zjamgs",234235);//Call the construction method with the parameter.System. out. println(caobj); Print output
Invoking methods with Reflection

Object. Method name (value-three-way);
Method M = c.getmethoed (methods name, parameter type ...);
M.invoke (object, parameter of method call) If the underlying method requires a shape parameter of 0, the supplied args array can be 0 or null in length.

Class C = Class. forname("Com.clazz.reflect.Student");Object obj = C. newinstance(); Creates a Sutdent object.Method Msetname = C. GetMethod("SetName", String. Class);//obj no conversion typeMsetname. Invoke(obj,"Zhangsan");//Call Method SetName, and pass the argument.Method Msetid = C. GetMethod("SetId"Int. Class);Msetid. Invoke(obj,409090202);System. out. println(obj);
My QR code is as follows, welcome to exchange discussion

You are welcome to pay attention to the "It question summary" subscription number. Every day to push the classic face test and interview tips, are dry! The QR code of the subscription number is as follows:

Reference:

Http://www.cnblogs.com/dennisit/archive/2013/02/26/2933508.html
http://blog.csdn.net/coder_pig/article/details/44784399
Http://www.codeceo.com/article/java-reflector-usage.html

Anatomy of the "54" Java reflection mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.