通过反射拿到属性值或是方法返回值

例子比较简单,不多说,直接贴代码

package demo;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectDemo {

    public static void main(String[] args) throws ClassNotFoundException  {
        Class class1 = Class.forName("demo.Test");
        try {
            Object obj = class1.newInstance();
            Field field = class1.getField("name");
            String a = (String) field.get(obj);
            System.out.println("属性值:" + a);
        } catch (InstantiationException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchFieldException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (SecurityException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalArgumentException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            Method test = class1.getDeclaredMethod("getName");
            Object invoke = test.invoke(class1.newInstance());
            System.out.println("方法返回值:" + invoke.toString());
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

class Test {
    public static String name = "小明";
    public String getName() {
        return name;
    }
}

这是打印
属性值:小明
方法返回值:小明

你可能感兴趣的:(java)