您的位置:首页 > 其它

通过反射(类类型)创建类的实例,调用类的方法,设置类的属性

2018-04-04 10:47 791 查看

Bean工厂

package com.test;

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

/**
* Bean工厂
*/
public class BeanFactory {

/**
* 创建实例
*
* @param clazz
* @return
*/
public static Object newInstance(Class<?> clazz) {
Object instance;
try {
instance = clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
return instance;
}

/**
* 方法调用
*
* @param obj
* @param method
* @param args
* @return
*/
public static Object invokeMethod(Object obj, Method method, Object... args) {
Object result;
try {
method.setAccessible(true);
result = method.invoke(obj, args);
} catch (Exception e) {
throw new RuntimeException(e);
}
return result;
}

/**
* 设置成员变量值
*
* @param obj
* @param field
* @param value
*/
public static void setField(Object obj, Field field, Object value) {
try {
field.setAccessible(true);
field.set(obj, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

}


method.setAccessible(true);

field.setAccessible(true);

使私有的成员和方法可以访问

测试

package com.test;

public class Student {

private int id;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

}

package com.test;

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

public class Test {

public static void main(String[] args) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException {

Class cl = Class.forName("com.test.Student");
//获得Student类的类类型

//通过类类型创建Student类的实例
Student student= (Student) BeanFactory.newInstance(cl);

//获得类中定义的属性
Field[] beanFields = cl.getDeclaredFields();
//遍历属性
for (Field beanField : beanFields) {
//设置属性,依赖注入的影子
BeanFactory.setField(student, beanField, Integer(1));
}
System.out.println(student.getId());
//
//		BeanFactory.setField(student, "name", "king");

}

private static Object Integer(int i) {
// TODO Auto-generated method stub
return i;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐