1,注意总结反射的概念与应用,特别是在项目中的应用。
java 反射和new的区别
首先Java反射是动态运行中,对于任意一个类都能知道这个类中所有的属性和方法包括私有属性和方法。然而new得到的对象不能调用私有方法和属性。
A a = new A();
A.class; //1.通过类.class获得Class对象
a.getClass(); //2./通过 实例名.getClass()获得Class对象
Class.forName("demo.A");//3.通过Class.forName(全路径)获得Class对象
反射的一个应用,根据Class类别和Result结果集返回Object对象,其中clazz是对象模型。
private static <T> T getObject(Class<T> clazz, ResultSet rs) {
T obj = null;
try{
obj = (T) clazz.newInstance();
Method[] methods = clazz.getDeclaredMethods();
String str = null;
String indexChar = null;
String fieldName = null;
String methodName = null;
for (Method method : methods) {
methodName = method.getName();
if(methodName.startsWith("set")){
str = methodName.substring(3);
indexChar= str.charAt(0)+"";
fieldName = str.replaceFirst(indexChar, indexChar.toLowerCase());
method.invoke(obj, rs.getObject(fieldName));
}
}
}catch(Exception e){
e.printStackTrace();
}
return obj;
}
1169

被折叠的 条评论
为什么被折叠?



