import java.io.FileInputStream; |
import java.lang.reflect.Field; |
import java.lang.reflect.Method; |
import java.text.SimpleDateFormat; |
import java.util.Date; |
import java.util.Properties; |
public class ReflectionDemo { |
@SuppressWarnings ({ "unchecked" , "rawtypes" }) |
public static void main(String[] args) throws Exception { |
// 创建一个Properties对象 |
Properties prop = new Properties(); |
while ( true ) { |
// 1.读取配置文件 |
prop.load( new FileInputStream( "config.properties" )); |
// 2.获取对应的字节码对象 |
Class<Profession> clz = (Class<Profession>) Class.forName(prop.getProperty( "classname" )); |
// 3.创建对应的实例对象 |
//Constructor con=clz.getConstructor(); |
Profession p = con.newInstance(); |
// 4.获取要设置的属性的名字 |
String[] attrnames = prop.getProperty( "attrname" ).split( "/" ); |
// 5.获取要设置的属性的值 |
String[] attrvalues = prop.getProperty( "attrvalue" ).split( "/" ); |
// 6. 遍历属性名的数组 |
for ( int i = 0 ; i < attrnames.length; i++) { |
//7. 获取当前属性的名字 |
String attrname = attrnames[i]; |
//8. 根据属性名来获取这个属性对象 |
Field f = clz.getDeclaredField(attrname); |
//9. 获取属性对象的声明类型 |
Class fclz = f.getType(); |
// 10.根据属性的名字来拼接对应的set方法的名字 |
String setMethodName = "set" + attrname.substring( 0 , 1 ).toUpperCase() + attrname.substring( 1 ); |
//11. 获取对应的set方法 |
Method setMethod = clz.getMethod(setMethodName, fclz); |
// 12.判断属性的类型,执行set方法 |
if (fclz == int . class || fclz.equals(Integer. class )) { |
setMethod.invoke(p, Integer.parseInt(attrvalues[i])); |
} else if (fclz == char . class || fclz.equals(Character. class )) { |
// setMethod.invoke(p, attrvalues[i].charAt(0)); |
setMethod.invoke(p, attrvalues[i].toCharArray()[ 0 ]); |
} else if (fclz.equals(Date. class )) { |
setMethod.invoke(p, new SimpleDateFormat( "yyyy-MM-dd" ).parse(attrvalues[i])); |
} else { |
setMethod.invoke(p, attrvalues[i]); |
} |
} |
// 13.获取指定的方法 |
Method m = clz.getDeclaredMethod(prop.getProperty( "methodname" ), null ); |
// 14.执行指定的方法 |
m.invoke(p, null ); |
|
Thread.sleep( 10000 ); |
} |
} |
} |
by: 发表于:2017-05-25 13:46:53 顶(0) | 踩(0) 回复
??
回复评论