反射基础

2017-04-16  本文已影响0人  岁月是首歌

Class

      //得到Class类的对象
     User  user=new User();
     Class clazz=str.getClass(); 
      
     Class clazz=User.Class;

     Class clazz=Class.forName("bao.User");

Field(得到属性)

    //获得类的单个属性
   Field field = clazz.getDeclaredField("name");
   Class type = field.getType();//获得属性的方法

   Field[] fields = clazz.getDeclaredFields();//获得类的所有属性
   for (Field field2 : fields) {
   System.out.println(field2.getName());//获得属性的名称
    }

SetField(设置属性)

  User user = (User)clazz.newInstance();//得到Class对象的一个实体
            field.setAccessible(true);//打破java访问权限
            field.set(user,"李四");//设置属性值
            

Map

    public  Object people(Class clazz,HashMap map){
        try {
            Field[] fields = clazz.getDeclaredFields();
            User user = (User) clazz.newInstance();
            Set set = map.entrySet();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                Entry entry = (Entry) iterator.next();
                String key = (String) entry.getKey();
                Object value = map.get(key);
                for (Field field : fields) {

                    if (field.getName().equals(key)) {
                        field.setAccessible(true);
                        field.set(user, value);
                    }
                }
            }
           return user;
        } catch (Exception e) {
            e.printStackTrace();
        }
     return null;
    }
//通过map集合赋值User集合所有的对象                                                         
      public ArrayList<User> people(Class clazz, ArrayList<HashMap> list)
            throws InstantiationException, IllegalAccessException {
        Field[] fields = clazz.getDeclaredFields();
        ArrayList<User> list2 = new ArrayList<User>();
        for (int i = 0; i < list.size(); i++) {
            User user = (User) clazz.newInstance();
            for (Field field : fields) {
                String key = field.getName();
                Object object = list.get(i).get(key);
                field.setAccessible(true);
                field.set(user, object);
            }
            list2.add(user);
        }
        return list2;
    }   

Method(得到类的方法)

        Method method = clazz.getDeclaredMethod("show",String.class); //方法加入参数
        method.invoke(object, "磊少");     

Constructor(使用类的构造方法)

        Class clazz = User.class;
        Constructor constructor = clazz.getDeclaredConstructor(String.class,int.class);//得到构造方法
        Object object = constructor.newInstance("磊少", 18);//得到构造方法的实体类
        System.out.println(object);
上一篇下一篇

猜你喜欢

热点阅读