java反射Demo

public class Test1 {

    /**
     * 根据class类实例化对象
     *
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    @Test
    public void test1() throws IllegalAccessException, InstantiationException {
        Class<?> c = String.class;
        Object str = c.newInstance();
        System.out.println(str);
        System.out.println(c.isInstance(str));
        if (str instanceof String) {
            System.out.println("Yes,i am instance of String.class");
        }
        if (!(str instanceof Integer)) {
            System.out.println("No no no,i am not instance of Integer.class");
        }
    }

    /**
     * 根据class获取构造方法,根据构造方法实例化对象
     *
     * @throws Exception
     */
    @Test
    public void test2() throws Exception {

        Class<?> c = String.class;
        Constructor constructor = c.getConstructor(String.class);
        Object str = constructor.newInstance("123456");
        System.out.println(str);
        System.out.println(c.isInstance(str));
        if (str instanceof String) {
            System.out.println("Yes,i am instance of String.class");
        }
        if (!(str instanceof Integer)) {
            System.out.println("No no no,i am not instance of Integer.class");
        }
    }

    /**
     * 根据class获取 类方法
     *
     * @throws Exception
     */
    @Test
    public void test3() throws Exception {
        Class<?> c = MethodClass.class;

        //getMethods()方法获取的所有pubic方法(包括父类)
        Method[] methods = c.getMethods();
        System.out.println("getMethods获取的方法:");
        for (Method m : methods) {
            System.out.println(m);
        }

        //方法返回类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法
        Method[] declaredMethods = c.getDeclaredMethods();
        System.out.println("getDeclaredMethods获取的方法:");
        for (Method m : declaredMethods) {
            System.out.println(m);
        }

        //获取methodClass类的add方法
        Object obj = c.newInstance();
        Method method = c.getMethod("add", int.class, int.class);
        Object invoke = method.invoke(obj, 1, 2);
        System.out.println(invoke);
        System.out.println(method);
    }

    /**
     * 根据Class获取属性
     *
     * @throws Exception
     */
    @Test
    public void test4() throws Exception {
        Class<?> c = MethodClass.class;

        //getFields()方法获取的所有pubic属性(包括父类)
        Field[] fields = c.getFields();
        System.out.println("field获取的属性:");
        for (Field f : fields) {
            System.out.println(f);
        }

        //方法返回类或接口声明的所有属性,包括公共、保护、默认(包)访问和私有属性,但不包括继承的方法
        Field[] declaredFields = c.getDeclaredFields();
        System.out.println("declaredFields获取的属性:");
        for (Field f : declaredFields) {
            System.out.println(f);
        }
        System.out.println("===============I am space line==============");

        //根据名称获取属性
        Field age = c.getField("name");
        System.out.println(age);
    }

    /**
     * 获取方法参数列表信息
     *
     * @throws Exception
     */
    @Test
    public void test5() throws Exception {

        Class<?> c = MethodClass.class;
        Method method = c.getMethod("add", int.class, int.class);

        //获取参数列表参数类型
        Class<?>[] parameterTypes = method.getParameterTypes();
        for (Class<?> parameterType : parameterTypes) {
            System.out.println(parameterType);
        }

        //获取方法参数列表参数名arg0,arg1...
        Parameter[] parameters = method.getParameters();
        for (Parameter parameter : parameters) {
            System.out.println(parameter.getName());
        }

        //获取方法参数列表参数名a,b...  真是java文件中的参数名
        LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
        String[] parameterNames = discoverer.getParameterNames(method);
        for (String parameterName : parameterNames) {
            System.out.println(parameterName);
        }
    }

    /**
     * 反射执行方法
     *
     * @throws Exception
     */
    @Test
    public void test6() throws Exception {
        Class<?> c = MethodClass.class;
        //创建methodClass的实例
        Object obj = c.newInstance();
        //获取methodClass类的add方法
        Method method = c.getMethod("add", int.class, int.class);
        //调用method对应的方法 => add(1,4)
        Object result = method.invoke(obj, 1, 4);
        System.out.println(result);
    }

    /**
     * 数组反射创建
     *
     * @throws Exception
     */
    @Test
    public void test7() throws Exception {
        Class<?> cls = Class.forName("java.lang.String");
        Object array = Array.newInstance(cls, 25);
        //往数组里添加内容
        Array.set(array, 0, "hello");
        Array.set(array, 1, "Java");
        Array.set(array, 2, "fuck");
        Array.set(array, 3, "Scala");
        Array.set(array, 4, "Clojure");
        //获取某一项的内容
        System.out.println(Array.get(array, 3));

    }

    Map<String, Integer> map = new HashMap<String, Integer>();


    @Test
    public void testT() throws Exception {

        Class c = Test1.class;
        Field f = c.getDeclaredField("map");
        System.out.println(f);
        System.out.println(f.getName());//map

        Class cl = f.getType();
        System.out.println("获得其类型:" + cl);

        /**
         *  Type getGenericType() 返回一个 Type 对象,它表示此 Field 对象所表示字段的声明类型。
         *  Type是Class的接口; java.util.Map<java.lang.String, java.lang.Integer>
         */
        Type t = f.getGenericType();//包含泛型的类型
        System.out.println(t);

        /**
         * Type这个类里面没有任何的方法,所以需要调用子类的方法,那么大的类型转到小的类型,需要强转!
         */
        ParameterizedType pt = (ParameterizedType) t;//强转到其子类

        /**
         *  Type[] getActualTypeArguments()
         返回表示此类型实际类型参数的 Type对象的数组。
         Type getOwnerType()
         返回 Type 对象,表示此类型是其成员之一的类型。
         Type getRawType()
         返回 Type 对象,表示声明此类型的类或接口。
         */

        t = pt.getRawType();//类型的类或接口
        System.out.println(t);
        Type[] ts = pt.getActualTypeArguments();

        for (Type type : ts) {
            System.out.println(type);

        }

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值