当前位置:网站首页>Get class files and attributes by reflection

Get class files and attributes by reflection

2022-07-05 06:36:00 Said it was all

The following code is to be obtained by using the reflection mechanism :

package com.zzuli;

/** * @author luoqingchen * @reate 2022-02-03-9:46 */
public class reflect01 {
    
    private boolean flag;
    public  int a;
    protected  String s;
}

Reflection acquisition :

public class Test01 {
    
    public static void main(String[] args) throws Exception {
    
      Class reflect=Class.forName("com.zzuli.reflect01");
        StringBuilder s=new StringBuilder();
        s.append(Modifier.toString(reflect.getModifiers())+" class "+reflect.getSimpleName());
        s.append("\n");
        s.append("{");
        s.append("\n");
       Field[] fields= reflect.getDeclaredFields();
       for (Field fs:fields){
    
           s.append("\t\t");
          s.append( Modifier.toString(fs.getModifiers()));
          s.append(" ");
          s.append(fs.getType().getSimpleName());
          s.append(" ");
          s.append(fs.getName());
          s.append("\n");

       }
        s.append("\n");
        s.append("}");
        System.out.println(s);
    }
}

Running results :
 Insert picture description here
Use reflection to get the attribute value in the class :

public class Test02 {
    

    public static void main(String[] args)  throws  Exception{
    
        Class reflect=Class.forName("com.zzuli.reflect01");
        Object obj=reflect.newInstance();
        // get attribute 
        Field field=reflect.getDeclaredField("a");
            // Setting property values 
        field.set(obj,8);
       Object obj2=field.get(obj);
        // Get the attribute value 
        System.out.println(obj2);
    }
}

Running results :( This example is getting public The value of the property )
 Insert picture description here
Want to get the value of the private attribute , Need to break the package :

public class Test02 {
    

    public static void main(String[] args)  throws  Exception{
    
        Class reflect=Class.forName("com.zzuli.reflect01");
        Object obj=reflect.newInstance();
        // get attribute 
        Field field=reflect.getDeclaredField("flag");
        // Break the package 
        field.setAccessible(true);
            // Setting property values 
        field.set(obj,true);
       Object obj2=field.get(obj);
        // Get the attribute value 
        System.out.println(obj2);
    }
}

Running results :
 Insert picture description here

原网站

版权声明
本文为[Said it was all]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140603261337.html