`

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

    博客分类:
  • JAVA
阅读更多
@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();
					}
				}
			}

		}
	}





分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics