用java的反射清空对象属性的值

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-1 09:47   622   0

@SuppressWarnings("unchecked")
public static void setObjectFieldsEmpty(Object obj) {
// 对obj反射
Class objClass = obj.getClass();
Method[] objmethods = objClass.getDeclaredMethods();
Map objMeMap = new HashMap();
for (int i = 0; i < objmethods.length; i++) {
Method method = objmethods[i];
objMeMap.put(method.getName(), method);
}
for (int i = 0; i < objmethods.length; i++) {
{
String methodName = objmethods[i].getName();
if (methodName != null && methodName.startsWith("get")) {
try {
Object returnObj = objmethods[i].invoke(obj,
new Object[0]);
Method setmethod = (Method) objMeMap.get("set"
+ methodName.split("get")[1]);
if (returnObj != null) {
returnObj = null;
}
setmethod.invoke(obj, returnObj);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}

}
}


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP