反射reflect-02

package com.ics.day10_14;

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

public class ReflectDemo {
    
    public static void main(String[] args) {
        String path = "com.ics.day10_14.User";
        try {
            Class<?> cla = Class.forName(path);
            
            //调用User的无参构造方法实例化一个对象
            User user = (User) cla.newInstance();//已过时
            
            //使用有参构造器
            Constructor<User> cons = (Constructor<User>) cla.getDeclaredConstructor(String.class, int.class);
            User user2 = cons.newInstance("zhangsan",18);
            System.out.println(user2.getName()+"---------"+user2.getAge());
            
            //通过反射api调用成员方法
            Method method = cla.getDeclaredMethod("setName", String.class);
            method.invoke(user, "lisi");
            System.out.println(user.getName());
            
            //通过反射操作属性
            Field field = cla.getDeclaredField("age");
            field.setAccessible(true);
            field.set(user, 30);
            System.out.println(user.getName()+"---------"+field.get(user));
            
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException 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 (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }    
    }

}

 

posted @ 2019-10-14 19:13  hsRick  阅读(164)  评论(0编辑  收藏  举报