如何使用反射从休眠对象中获取数据?
How do I use reflection to get data out of a hibernate object?
这是我在使用反射时遇到的问题的示例。这是一个简单的案例,但我最终需要的是即时动态构建方法名称......但即使是这个简单的案例我也无法开始工作!
Client1 cData = (Client1) session.get(Client1.class, 1);
int cType = cData.getClientType();
int cType2 = -1;
Method method[] = null;
Method getCTypeMethod = null;
try {
method = cData.getClass().getMethods();
for (Method m : method){
System.out.println(m.getName()); // displays getClientType
}
getCTypeMethod = cData.getClass().getMethod("getClientType", int.class);
if (getCTypeMethod != null){
cType2 = (int) getCTypeMethod.invoke(cData, int.class);
}
} catch (Exception e) {
e.printStackTrace();
}
assertEquals(cType, cType2);
行:
getCTypeMethod = cData.getClass().getMethod("getClientType", int.class);
总是抛出异常:
java.lang.NoSuchMethodException: Client1.getClientType(整数)
方法getMethod接收参数类,不是return类型,你的getClientType
接收一个int?
如果不行,试试:
cData.getClass().getMethod("getClientType");
这是我在使用反射时遇到的问题的示例。这是一个简单的案例,但我最终需要的是即时动态构建方法名称......但即使是这个简单的案例我也无法开始工作!
Client1 cData = (Client1) session.get(Client1.class, 1);
int cType = cData.getClientType();
int cType2 = -1;
Method method[] = null;
Method getCTypeMethod = null;
try {
method = cData.getClass().getMethods();
for (Method m : method){
System.out.println(m.getName()); // displays getClientType
}
getCTypeMethod = cData.getClass().getMethod("getClientType", int.class);
if (getCTypeMethod != null){
cType2 = (int) getCTypeMethod.invoke(cData, int.class);
}
} catch (Exception e) {
e.printStackTrace();
}
assertEquals(cType, cType2);
行:
getCTypeMethod = cData.getClass().getMethod("getClientType", int.class);
总是抛出异常: java.lang.NoSuchMethodException: Client1.getClientType(整数)
方法getMethod接收参数类,不是return类型,你的getClientType
接收一个int?
如果不行,试试:
cData.getClass().getMethod("getClientType");