Field[] fds = elbook392d.getClass().getDeclaredFields(); // elbook392d為一類對象
for (int i = 0; i < fds.length; i++) {
if ("java.math.BigDecimal".equals(fds[i].getType().getName())) { // 得到所有類型為BigDecimal的字段
try {
//方法名称
String getMethodName = "get"+ fds[i].getName().substring(0,1).toUpperCase() +
fds[i].getName().substring(1,fds[i].getName().length());
String setMethodName = "set"+ fds[i].getName().substring(0,1).toUpperCase() +
fds[i].getName().substring(1,fds[i].getName().length());
//得到方法
Class[] getMethodParameterClass = {};
Method getMethod = elbook392d.getClass().getDeclaredMethod(getMethodName, getMethodParameterClass);
Class[] setMethodparameterClass = {fds[i].getType()};
Method setMethod = elbook392d.getClass().getDeclaredMethod(setMethodName, setMethodparameterClass);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
for (int i = 0; i < fds.length; i++) {
if ("java.math.BigDecimal".equals(fds[i].getType().getName())) { // 得到所有類型為BigDecimal的字段
try {
//方法名称
String getMethodName = "get"+ fds[i].getName().substring(0,1).toUpperCase() +
fds[i].getName().substring(1,fds[i].getName().length());
String setMethodName = "set"+ fds[i].getName().substring(0,1).toUpperCase() +
fds[i].getName().substring(1,fds[i].getName().length());
//得到方法
Class[] getMethodParameterClass = {};
Method getMethod = elbook392d.getClass().getDeclaredMethod(getMethodName, getMethodParameterClass);
Class[] setMethodparameterClass = {fds[i].getType()};
Method setMethod = elbook392d.getClass().getDeclaredMethod(setMethodName, setMethodparameterClass);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
得到CcassRate字段, 我要做這樣的動作.`` (得到此屬性值, 做個變動, 在設置到此屬性.)
elbook392d.setCcassRate(elbook392d.getCcassRate().setScale(2)); 用反射如何調用? 我用這種方式試, 但坐試右試還是試不通. 呵呵.``
//getMethod.invoke(elbook392d.getClass().newInstance(), null);
//setMethod.invoke(elbook392d.getClass().newInstance(), );
我這樣做的目的是: 假如表中有100個字段, 其中有50個字段是數字類型, 直接用這種方式,
能一個迭代就將所有數字類型的屬性值更改并設置到對象中, 而不用一個一個屬性去寫.
如果這種行不通,有什么其他方式嗎? 謝謝哦.
BigDecimal newValue = oldValue.setScale(2);Object[] inputSetMethodParameterClass = {newValue};
setMethod.invoke(elbook392d,inputSetMethodParameterClass);