反射基础

反射

反射能在运行时获取任意一个类的所有属性和方法,前提是他能获取到类的Class对象

/*反射的基本使用*/
public class ReflectDemo {
    private String privateFiled = "private filed qaq";

    public String publicFiled = "public filed qaq";

    boolean BoolFiled = true;

    private void privateMethod() {
        System.out.println("private method");
    }

    public void publicMethod(String str) {
        System.out.println("public method " +str);
    }

    public void publicMethodWithoutParam() {
        System.out.println("public method without param");
    }

    public ReflectDemo() {}

    public ReflectDemo(String str){};

    private ReflectDemo(String str1,String str2){};
}

public class TestReflect {
    public static void main(String[] args) {
        try {
            Class clazz = Class.forName("com.reda.reflect.ReflectDemo");
            //调用构造方法公有构造方法
            Constructor ctor1 = clazz.getConstructor();
            //带参数共有构造方法
            Constructor ctor2 = clazz.getConstructor(String.class);
            //私有构造方法
            Constructor ctor3 = clazz.getDeclaredConstructor(String.class,String.class);
            ctor3.setAccessible(true);

            Object obj = ctor1.newInstance();
            Object obj2 = ctor2.newInstance("qaq");
            Object obj3 = ctor3.newInstance("1","2");
            //调用公有域
            Field field1 = clazz.getField("publicFiled");
            System.out.println(field1.get(obj));
            //调用包可见域
            Field field2 = clazz.getDeclaredField("BoolFiled");
            System.out.println(field2.getBoolean(obj2));
            //调用私有域
            Field field3 = clazz.getDeclaredField("privateFiled");
            field3.setAccessible(true);
            System.out.println(field3.get(obj2));
            //调用方法public方法
            Method method1 = clazz.getMethod("publicMethodWithoutParam");
            method1.invoke(obj);
            //调用带参数的public方法
            Method method2 = clazz.getMethod("publicMethod",String.class);
            method2.invoke(obj3,"qaq");
            //调用私有方法
            Method privateMethod = clazz.getDeclaredMethod("privateMethod");
            privateMethod.setAccessible(true);
            privateMethod.invoke(obj3);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容