package com.learn.reflection;
/**
* 通过反射来调用的实体类
* @author jiadong
*
*/
public class RefReal {
private int intReal;
private String strReal;
public int getIntReal() {
System.out.println(intReal);
return intReal;
}
public void setIntReal(int intReal) {
System.out.println("Method :setIntReal "+intReal);
this.intReal = intReal;
}
public String getStrReal() {
return strReal;
}
public void setStrReal(String strReal) {
System.out.println("Method :setStrReal "+strReal);
this.strReal = strReal;
}
public void otherMethod(int i,String strReal){
System.out.println("Method: otherMethod "+ i+strReal);
}
}
package com.learn.reflection;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
import junit.framework.TestCase;
/**
* 测试反射的类
* @author jiadong
*
*/
public class ReflectionTest extends TestCase {
private String proPath = "reflectionClass.properties" ;
/**
* reflectionClass.properties 的内容为:
* className =com.learn.reflection.RefReal
*
*/
@SuppressWarnings("unchecked")
public void test(){
//read form properties file
java.io.InputStream is = ReflectionTest.class.getClassLoader().getResourceAsStream(proPath);
Properties properties = new Properties();
try {
properties.load(is);
String className = properties.getProperty("className");
Class c = Class.forName(className);
Object o = c.newInstance();
Method[] methods = c.getMethods();
for(Method method :methods){
if(method.getName().contains("set")){
System.out.println("������:"+method.getName()+"������������:"+method.getReturnType());
System.out.println("�����IJ�������Ϊ:"+method.getParameterTypes()[0]);
if(method.getParameterTypes()[0].toString().equals("int")){
method.invoke(o, 123);
}
}
}
} catch (IOException e) {
System.out.println("read error");
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
posted on 2008-09-18 14:21
jiadong 阅读(1801)
评论(0) 编辑 收藏 所属分类:
OTHERS