反射就是把java类中各种成分映射成相应的java类
Constructor:
Method:
Field:
1、java的反射用法:
①找到类:Class cl = Class.forName("java.util.Date");②创建对象(要求这个类中含有空参数的构造方法):Object obj = cl.newInstence();
③根据名称和参数找方法:Method method1 = cl.getMethod("getTime");//如果没有参数不用写第二个参数如果有参数的如:Method method2 = cl.getMethod("setTime",long.class);
④在某个对象上面执行方法,Object result = method1.invoke(obj);//如果有参数的Object result = method2.invoke(obj,21317362721);
执行的方如果有返回值,将返回值返回,否则返回null
⑤如果invoke方法的第一个参数为NULL,说明该Method对象对应的是一个静态的方法
invoke(o,Object...args)
}
2、封装javaBeen
public static void beenObject(Object object, String[] fields, Object[] params) throws Exception { Class<?> cl = object.getClass(); for (int i = 0; i < fields.length; i++) { StringBuffer buffer = new StringBuffer(); Field field = cl.getDeclaredField(fields[i]); Class<?> paramType = field.getType(); buffer.append("set"); buffer.append(fields[i].substring(0, 1).toUpperCase()); buffer.append(fields[i].substring(1)); Method method = cl.getDeclaredMethod(buffer.toString(), paramType); method.invoke(object, params[i]); } }或
public Object mysetter1(String s,Map<String,Object> k_v) throws Exception{ Class o = Class.forName(s); Object obj = o.newInstance(); Iterator<String> it = k_v.keySet().iterator(); Pattern pattern = Pattern.compile("^\\w"); while(it.hasNext()){ String pro = it.next(); Matcher matcher = pattern.matcher(pro); String m_name = "set"; if(matcher.find()){ m_name += matcher.replaceFirst(matcher.group(0).toUpperCase()); } o.getMethod(m_name, k_v.get(pro).getClass()).invoke(obj, k_v.get(pro)); } return obj; }