Home >Java >javaTutorial >Reflection basics of java

Reflection basics of java

黄舟
黄舟Original
2017-02-24 09:51:161053browse


1. What is reflection


The reflection mechanism is in the running state, for any Class, you can know all the methods and attributes of this class; for any object, you can call any of its methods and attributes. This 0d057defeb9961d31f5d46289da17a15 information and dynamically call the object's method is called Java's reflection mechanism.

2. The role of reflection

  • 1. Decompilation: .class–>java

  • ##2 , Access the properties, methods, constructors, etc. of objects through the reflection mechanism

3. Specific implementation of reflection

3. 1 Reflection-related classes

  • java.lang.Class;

  • java.lang.reflect.Constructor;

  • java.lang.reflect .Field;

  • java.lang.reflect.Method;

  • ##java.lang.reflect.Modifier;
  • 3.2 Three ways to obtain large Class objects

Since any class is a subclass of Object and there is getClass in Object, you can obtain

Class objects - public final native Class6b3d0130bba23ae47fe2b8e8cddf0195 getClass();
-

package com.chb.reflectTest;public class Test {
    public static void main(String[] args) throws Exception {        //第一种方式:
        Class<?> c1 = Class.forName("com.chb.reflectTest.Test");    //第二种方式:java中每个类都有class属性
        Class<?> c2 = Test.class;        //第三种方式:每个对象都与getClass()方法
        Class<?> c3 = new Test().getClass();
    }
}

3.3 Create an object

 After obtaining the

Class

object, use it to create an object, call the no-argument constructor through newInstance() to create the object, newInstance() returns An Object:

Class<?> c1 = Class.forName("com.chb.reflectTest.Test");Object o1 = c1.newInstance();
3.4. Obtaining data

It is divided into all attributes and specified attributes

3.4.1. Obtaining all attributes

    Get the modifications
    • First get the modification object through getModifiers() of the attribute,
    • Then through java.long. reflect.Modifier's toString() prints classes and attribute modifications (public, static, final, etc.).
    Get attributes
    • Get all attributes: Return a Fielded array* through getDeclaedFields() of the Class object *.
    Get the type of attribute:
    • Through getType() of the attribute object (Field object)
    • Class<?> cString = Class.forName("java.lang.String");
              //获取累的修饰和名称
              System.out.print(Modifier.toString(cString.getModifiers())+" class " + cString.getSimpleName()+"{\n");
              //获取所有属性
              Field[] fields = cString.getDeclaredFields();
              for (Field field : fields) {
                  System.out.print("\t");
                  System.out.print(
                          Modifier.toString(field.getModifiers())+" "//属性的修饰
                        + field.getType().getSimpleName()+" "
                        + field.getName()+"\n");           
              }
              System.out.println("}");
    3.4.2 Get the specified attribute

Create a test object:

Note: I defined two attributes in the Use class, one public, A private, for the next test reflection can break the encapsulation

package com.chb.reflectTest;public class User {    
private String name;    
public  String nickName;    
public User() {}    
public User(String name, String nickName) {        
this.name = name;        
this.nickName = nickName;
    }
    setter getter...

}
Comparison between traditional attribute acquisition and acquisition through reflection:

package com.chb.reflectTest;import java.lang.reflect.Field;public class Test1 {
    public static void main(String[] args) throws Exception {
        //传统获取属性的值
        //1、通过getter,setter
        User user1 = new User();
        user1.setName("lisi");
        System.out.println(user1.getName());
        //2、直接调用属性
        User user2 = new User();
        user2.nickName = "癞皮狗";
        System.out.println(user2.nickName);
        //=========================================
        //通过反射来设置,获取属性。
        Class<User> c1 = (Class<User>) Class.forName("com.chb.reflectTest.User");
        User user = c1.newInstance();
        Field nickField = c1.getDeclaredField("nickName");
        nickField.set(user, "123");
        System.out.println(nickField.get(user));

        Field nameFiled = c1.getDeclaredField("name");
        //Exception in thread "main" java.lang.IllegalAccessException: 
        Class com.chb.reflectTest.Test1 can not access a member of class com.chb.reflectTest.User with modifiers "private"
        nameFiled.setAccessible(true);
        nameFiled.set(user, "oup");
        System.out.println(nameFiled.get(user));

    }
}

Set the value of the attribute through reflection, distinguishing attributes Modification range, private cannot be set directly

An access error will occur, which is the safe access mechanism of java, error message:

Exception in thread "main" java.lang.IllegalAccessException: Class com.chb.reflectTest.Test1 can not access a member of class com.chb.reflectTest.
User with modifiers "private"

We use a method to break the encapsulation of java:

nameFiled.setAccessible(true);

1. What is reflection?

The reflection mechanism is in the

running state

. For any class, you can know all the methods and attributes of this class; for any object , you can call any of its methods and attributes. This 087c0163c1694010ba0d610b7e814433 information and dynamically calling the object method are called Java's reflection mechanism. 2. The role of reflection

    1. Decompilation: .class–>java
  • ##2 , Access the properties, methods, constructors, etc. of objects through the reflection mechanism
  • 3. Specific implementation of reflection
3. 1 Reflection-related classes

java.lang.Class;
  • java.lang.reflect.Constructor;
  • java.lang.reflect .Field;
  • java.lang.reflect.Method;
  • ##java.lang.reflect.Modifier;

  • 3.2 Three ways to obtain large Class objects

  • Since any class is a subclass of Object and there is getClass in Object, you can obtain

Class

objects - public final native Class6b3d0130bba23ae47fe2b8e8cddf0195 getClass(); -

package com.chb.reflectTest;public class Test {
    public static void main(String[] args) throws Exception {        //第一种方式:
        Class<?> c1 = Class.forName("com.chb.reflectTest.Test");        //第二种方式:java中每个类都有class属性
        Class<?> c2 = Test.class;        //第三种方式:每个对象都与getClass()方法
        Class<?> c3 = new Test().getClass();
    }
}
3.3 Create an object
 After obtaining the

Class

object, use it to create an object, call the no-argument constructor through newInstance() to create the object, and newInstance() returns An Object:

Class<?> c1 = Class.forName("com.chb.reflectTest.Test");Object o1 = c1.newInstance();

3.4. Obtaining data It is divided into all attributes and specified attributes

3.4.1. Obtaining all attributes

Get the modifications

  • First get the modification object through getModifiers() of the attribute,
    • Then through java.long. reflect.Modifier's toString() prints classes and attribute modifications (public, static, final, etc.).

    • Get attributes
  • Get all attributes: Return a Fielded array* through getDeclaedFields() of the Class object *.
    • Get the type of attribute:
      • 通过属性对象(Field对象)的getType()

    Class<?> cString = Class.forName("java.lang.String");
            //获取累的修饰和名称
            System.out.print(Modifier.toString(cString.getModifiers())+" class " + cString.getSimpleName()+"{\n");
            //获取所有属性
            Field[] fields = cString.getDeclaredFields();
            for (Field field : fields) {
                System.out.print("\t");
                System.out.print(
                        Modifier.toString(field.getModifiers())+" "//属性的修饰
                      + field.getType().getSimpleName()+" "
                      + field.getName()+"\n");           
            }
            System.out.println("}");

    3.4.2 获取指定属性

    创建测试对象:
    注意: 我在Use类中定义了两个属性, 一个public ,一个private ,是为了下一个测试反射可以打破封装性

    package com.chb.reflectTest;public class User {    
    private String name;    
    public  String nickName;    
    public User() {}    
    public User(String name, String nickName) {        
    this.name = name;        
    this.nickName = nickName;
        }
        setter getter...
    
    }

    传统属性的获取和通过反射获取对比:

    package com.chb.reflectTest;import java.lang.reflect.Field;public class Test1 {
        public static void main(String[] args) throws Exception {
            //传统获取属性的值
            //1、通过getter,setter
            User user1 = new User();
            user1.setName("lisi");
            System.out.println(user1.getName());
            //2、直接调用属性
            User user2 = new User();
            user2.nickName = "癞皮狗";
            System.out.println(user2.nickName);
            //=========================================
            //通过反射来设置,获取属性。
            Class<User> c1 = (Class<User>) Class.forName("com.chb.reflectTest.User");
            User user = c1.newInstance();
            Field nickField = c1.getDeclaredField("nickName");
            nickField.set(user, "123");
            System.out.println(nickField.get(user));
    
            Field nameFiled = c1.getDeclaredField("name");
            //Exception in thread "main" java.lang.IllegalAccessException: 
            Class com.chb.reflectTest.Test1 can not access a member of class com.chb.reflectTest.User with modifiers "private"
            nameFiled.setAccessible(true);
            nameFiled.set(user, "oup");
            System.out.println(nameFiled.get(user));
    
        }
    }

    通过反射来设置属性的值, 区别属性的修饰范围, 私有的不可以直接设置
    会出现访问错误, 也就是java的安全访问机制,报错:

    Exception in thread "main" java.lang.IllegalAccessException: Class com.chb.reflectTest.Test1 can not access a member of class com.chb.reflectTest.
    User with modifiers "private"

    我们通过一个方法·来打破java的封装性:

    nameFiled.setAccessible(true);

     以上就是java之反射基础的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Java reflection advancedNext article:Java reflection advanced