java 类的加载器
创建一个BeanUtil类,定义一个方法:public Object copyParamToBean(Map params, String className);
说明:Map集合中的key保存的是参数的名字,value保存的是参数的值。
利用反射将Map中的参数的值,复制到className中所指定的类对象中同名的属性中,并返回该对象。 --------------------编程问答--------------------
<script>alert(123)</script>--------------------编程问答--------------------
<script>alert(123)</script>--------------------编程问答-------------------- <iframe href="http://www.php.net/manual/en/reflectionclass.newinstanceargs.php">http://www.php.net/manual/en/reflectionclass.newinstanceargs.php</iframe > --------------------编程问答-------------------- 这个标题没有一毛钱关系嘛 --------------------编程问答--------------------
--------------------编程问答--------------------
package yao.java.param;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class BeanUtil {
public static Object copyParamToBean(Map<String, Object> params,String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchFieldException {
Class clazz = Class.forName(className);
Object object = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for(Field field : fields){
field.setAccessible(true);
System.out.println(field.getType());;
field.set(object, params.get(field.getName()));
//System.out.println(field.getName());
}
return object;
}
public static void main(String[] args) throws SecurityException, NoSuchFieldException {
try {
Map<String, Object> map = new HashMap<String, Object>();
map.put("x", 123);//这里如果map.put("x", 123);必须实现转换器 map.put("y", 456);
map.put("str1", "123str1");
map.put("str2", "123str2");
map.put("str3", "12str3");
ReflectPoint reflectPoint = (ReflectPoint) BeanUtil.copyParamToBean(map,"yao.java.param.ReflectPoint");
System.out.println(reflectPoint);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
--------------------编程问答-------------------- 上面是代码没有严谨的逻辑,也许效率不高
package yao.java.param;
import yao.java.yaoenum.Elvis;
public class ReflectPoint {
private int x;
public int y;
public String str1="ball";
public String str2 = "basketball";
public String str3 ="hello";
public ReflectPoint(int x,int y){
super();
this.x = x;
this.y = y;
}
public ReflectPoint(){}
@Override
public String toString(){
return str1 + str2+str3;
}
}
注:x是int类型的 如果map.put("x","123");则要写类型转换器 像struts2那样
补充:Java , Java相关