-
- package com.farrand.velocity.entity;
- public class VelocityUser {
- private Integer id;
- private String username;
- private String password;
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- }
- import java.lang.reflect.Method;
- import org.apache.commons.lang.StringEscapeUtils;
- import com.farrand.velocity.entity.VelocityUser;
- public class Test {
- private static String clzName;
- /**
- * 构造方法
- * @param asClzName
- * 要过滤的类名字
- */
- public Test(String asClzName) {
- Test.clzName = asClzName;
- }
- /**
- * 用于取得被过滤后的类的方法
- * @return 返回类型为Object
- */
- public static Object getPropFilteredClz(Object classNameObj, Object[] obj) {
- try {
- Class clz = Class.forName(clzName);
- Method[] methods = clz.getDeclaredMethods();
- Object lsTemp = null;
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().startsWith("g")) {
- // 反射调用get***方法
- String methodSetName = methods[i].getName().replace("get", "set");
- Method setMethod = clz.getMethod(methodSetName, methods[i].invoke(classNameObj, obj).getClass());
- if (methods[i].invoke(classNameObj, obj) instanceof String) {
- lsTemp = StringEscapeUtils.escapeHtml((methods[i].invoke(classNameObj, obj).toString()));
- } else {
- lsTemp = methods[i].invoke(classNameObj, obj);
- }
- setMethod.invoke(classNameObj, lsTemp);
- }
- }
- } catch (Exception ex) {
- // TODO
- }
- // 返回过滤后的类的实例
- return classNameObj;
- }
- public static Object getPropFilteredClz(Object classNameObj) {
- Object propFilteredObj = getPropFilteredClz(classNameObj, null);
- return propFilteredObj;
- }
- public static void main(String[] args) {
- // 此处为测试方法,比如传入的类型名为VelocityUser
- VelocityUser userInfo = new VelocityUser();
- userInfo.setId(5);
- userInfo.setUsername("wan<br>mei");
- userInfo.setPassword("shijie");
- new Test("com.farrand.velocity.entity.VelocityUser");
- // 此处过滤返回后,类型转换为VelocityUser型对象
- VelocityUser mzk = (VelocityUser) Test.getPropFilteredClz(userInfo);
- System.out.println("过滤后id:" + mzk.getId());
- System.out.println("过滤后username:" + mzk.getUsername());
- System.out.println("过滤后password:" + mzk.getPassword());
- }
- }
运行结果:
过滤后id:5
过滤后username:wan<br>mei
过滤后password:shijie