Java反射应用

来源:互联网 发布:死亡岛有网络怎么联机 编辑:程序博客网 时间:2024/06/11 23:26

通过配置文件运行类中的方法

 

反射:

    需要有配置文件配合使用。

    class.txt代替。

    并且你知道有两个键。

    className

methodName

 

class.txt文件中的内容:

className=cn.iponkan.test.User

methodName=show

 

具体用法:

                // 加载键值对数据Properties prop = new Properties();FileReader fr = new FileReader("class.txt");prop.load(fr);fr.close();// 获取数据String className = prop.getProperty("className");String methodName = prop.getProperty("methodName");// 反射Class c = Class.forName(className);Constructor con = c.getConstructor();Object obj = con.newInstance();// 调用方法Method m = c.getMethod(methodName);m.invoke(obj);

给出ArrayList<Integer>的一个对象,在这个集合中添加一个字符串数据,如何实现呢?

public class ArrayListReflect {public static void main(String[] args) throws NoSuchMethodException,SecurityException, IllegalAccessException,IllegalArgumentException, InvocationTargetException {// 创建集合对象ArrayList<Integer> array = new ArrayList<Integer>();Class c = array.getClass(); // 集合ArrayList的class文件对象Method m = c.getMethod("add", Object.class);m.invoke(array, "hello"); // 调用array的add方法,传入的值是hellom.invoke(array, "world");m.invoke(array, "java");System.out.println(array);}}

//运行结果:[hello, world, java]


写一个方法:public void setProperty(Object obj, String propertyName, Object value){}

此方法可将obj对象中名为propertyName的属性的值设置为value


public void setProperty(Object obj, String propertyName, Object value)throws NoSuchFieldException, SecurityException,IllegalArgumentException, IllegalAccessException {// 根据对象获取字节码文件对象Class c = obj.getClass();// 获取该对象的propertyName成员变量Field field = c.getDeclaredField(propertyName);// 取消访问检查field.setAccessible(true);// 给对象的成员变量赋值为指定的值field.set(obj, value);}

调用:

Person p = new Person();

setProperty(p, "age", 22);



原创粉丝点击