日期:2014-05-20  浏览次数:20679 次

反射方法
public static void main(String[] args){
  User u = new User();
  User t = new User();
  t = findIt(u);
}
class Object findIt(Object obj){
  String test = "userId:1;userName:frank;password:1234;date:1328241269734;count:1";
  //如何实现



这个代码如何实现,通过u传给findIt方法把字符串中的值写道t当中返回

------解决方案--------------------
String[] str = test.split(";");
Class<User> clazz = User.class;
User user = new User();
for(String str1;str){
Field field = clazz.getField(str1.split(":")[0]);//根据字段名获取字段对象
field.setAccessible(true);//将该字段设置为可访问
field.setValue(user,str1.split(":")[1]);//给user对象上的该字段赋值
};
------解决方案--------------------
String[] str = test.split(";");
Class<User> clazz = User.class;
User user = new User();
for(String str1;str){
Field field = clazz.getField(str1.split(":")[0]);//根据字段名获取字段对象
field.setAccessible(true);//将该字段设置为可访问
field.set(user,str1.split(":")[1]);//给user对象上的该字段赋值
};
搞错了 field.set(user,str1.split(":")[1]);//给user对象上的该字段赋值(这个地方改一下)
------解决方案--------------------
探讨
public Object findObjectByCookie(String key,Object obj) {
String test ="userId:1;userName:frank;password:1234;date:1328241269734;count:1";
String[] objs = test.split(";");
Object objReturn = ……

------解决方案--------------------
Java code
public class ReflectTest {

    public static void main(String[] args) {
        User user = (User) test(
                "userId:1;userName:frank;password:1234;date:1328241269734;count:1",
                User.class);
        System.out.println(user.getUserName());
    }

    private static Object test(String userStr, Class<?> clazz) {
        try {
            String[] str = userStr.split(";");
            Object user = clazz.newInstance();// 初始化一个对象
            Field[] fields = clazz.getDeclaredFields();// 获取该对象所有字段
            for (String str1 : str) {
                for (Field field : fields) {
                    String c = field.getType().getName();// 字段类型
                    if (field.getName().equals(str1.split(":")[0])) {
                        field.setAccessible(true);// 把字段设置为可访问
                        if (c.equals("int")) {
                            field.setInt(user, Integer
                                    .parseInt(str1.split(":")[1]));
                        } else if (c.equals("java.lang.String")) {
                            field.set(user, str1.split(":")[1]);
                        } else if (c.equals("java.lang.long")) {
                            field.setLong(user, Long
                                    .parseLong(str1.split(":")[1]));
                        }
                    }
                }
            }
            return user;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}