2018-06-19 java 反射的简单使用

public class myRect {
    public static class Test implements Comparable {
        private String name;

        public Test(String name) {
            this.name = name;
        }

        public void sout(){
            System.out.println("我是谁?"+name);
        }

        public int compareTo(Test o) {
            return 0;
        }
    }

    public static void main(String[] args) {
        try {
            //打印类名,内部类用$
            System.out.println(Test.class);
            //需要类名
            final Class aClass = Class.forName("day05.myRect$Test");
            //调用有参构造,无参直接aClass.newInstance()
            final Constructor constructor = aClass.getConstructor(String.class);
            final Test test = (Test) constructor.newInstance("测试类");
            //动态获取方法
            final Method method = aClass.getMethod("sout");
            method.invoke(test);
            //修改公共变量
            //final Field name = aClass.getField("name");
            //修改私有变量,在创建类时没有创建set方法
            final Field name = aClass.getDeclaredField("name");
            name.setAccessible(true);
            name.set(test,"ccc");
            test.sout();
            //获取class的类加载器
            System.out.println(aClass.getClassLoader());
            //打印所有接口
            final Class[] interfaces = aClass.getInterfaces();
            for (Class class1: interfaces
                 ) {
                System.out.println(class1);
            }
            //打印父类
            System.out.println(aClass.getGenericSuperclass());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(2018-06-19 java 反射的简单使用)