现在的位置: 首页 > 综合 > 正文

利用java反射机制进行对象操作

2018年03月20日 ⁄ 综合 ⁄ 共 1943字 ⁄ 字号 评论关闭
 我们经常使用COMMONS-BEANUTILS包来进行bean的操作,例如从map到bean获从bean到map的映射,那么实现的原理是什么呢,下面举个简单的操作的例子;首先,我建立一个bean
public class Bean {
private String test1;

private String getTest1() {
return test1;
}

private void setTest1(String test1) {
this.test1 = test1;
}
}

上面这个例子比较极端,利用我们平常的JAVA操作是不可能通过这两个私有方法进行设置和获取值的,但是我们利用JAVA反射机制却可以非常方便的操作。
下面,我将全部利用JAVA的反射来进行对象的创建,以及对它的操作;这里我们假设这个Bean我们只能得到名称,例如,我们是从配置文件中得到的名称,公司的COMMAND框架中receiver的配置就是如此,配置了receiver的名称和要执行的方法,我们无论他是否是私有的还是共有的都可以访问。
public class TestClass {

/**
* @param args
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InstantiationException
*/
public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException {
//1.0得到bean的Class对象
Class beanClass=Class.forName("org.test.t.Bean");
//2.0利用构造函数构造一个Bean对象
Constructor bc=beanClass.getConstructor(null);
Bean b=(Bean) bc.newInstance(null);
/**
* 也可以这样构造
* Bean b=Class.forName("org.test.t.Bean").newInstance();
*/

//3.0通过getDeclaredMethod方法得到要执行的方法(public/protected/private/默认),要执行的方法的函数名字是第一个参数指定,第二个参数指定该函数带有的参数
//如果只需要得到公共成员方法,则直接调用getMethod方法
Method setMethod=beanClass.getDeclaredMethod("setTest1", new Class[]{String.class});
Method getMethod=beanClass.getDeclaredMethod("getTest1", null);
//4.0 如果要访问私有的方法,所以我们在这里将可访问设置为true,则JVM不会执行访问控制检查;如果是共有方法则不需要设置
setMethod.setAccessible(true);
//5.0用得到的方法对象在第2步中构造的对象中执行
setMethod.invoke(b, new Object[]{"hello"});
System.out.println(getMethod.isAccessible());
getMethod.setAccessible(true);
System.out.println(getMethod.isAccessible());
System.out.println(getMethod.invoke(b, null));

}

}
上面红色部分是获取所有public/private/protected/默认 方法的函数,如果只需要获取public方法,则可以调用getMethod.

上面粉红色的方法是将要执行的方法对象设置是否进行访问检查,也就是说对于public/private/protected/默认 我们是否能够访问。值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。值为 false 则指示反射的对象应该实施 Java 语言访问检查。
如果是共有方法,当然不需要设置。

抱歉!评论已关闭.