将泛型对象转换为泛型类

时间:2014-04-14 18:14:39

标签: java android reflection generic-programming

我想将一个泛型对象传递给我的方法,并让它获取属性名称,类型和值。

这是我的班级

public class Login {

    public String token;   
    public String customerid;
    public Class1 class1;
    public Class2 class2;

    public class Class1 {
        public Class3 class3;
        public String string1;

        public class Class3 {
                public int int1;
                public String string2;
                public String string3;
        }
    }

    public class Class2 {
        public int int1;
        public String string2;
        public String string3;
    }
}

我希望输出看起来像这样

User Preferences customerid - class java.lang.String - 586969
User Preferences token - class java.lang.String - token1
User Preferences string1 - class java.lang.String - string1Value
User Preferences string2 - class java.lang.String - string2Value
User Preferences string3 - class java.lang.String - string3Value

我现在的代码给了我一些问题。这是代码:

    try {
        // Loop over all the fields and add the info for each field
        for (Field field : obj.getClass().getDeclaredFields()) {
            if(!field.isSynthetic()){
                field.setAccessible(true);
                System.out.println("User Preferences " + field.getName() + " - " + field.getType() + " - " + field.get(obj));
            }
        }

        // For any internal classes, recursively call this method and add the results
        // (which will in turn do this for all of that subclass's subclasses)
        for (Class<?> subClass : obj.getClass().getDeclaredClasses()) {
            Object subObject = subClass.cast(obj); // ISSUE
            addUserPreferences(subObject, prefs);
        }
    }catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }catch(ClassCastException e) {
        e.printStackTrace();
    }

获取subObject,在本例中为Class1Class2,并将其传递给方法是我遇到的问题。我尝试过一个类而不是一个对象,但后来我无法从类中获取该对象。

无论如何将我传入的对象转换为子类?

由于

2 个答案:

答案 0 :(得分:0)

您有几个选择:


一种选择是考虑定义一些定义提供用户偏好的对象的接口,例如:

interface UserPreferenceProvider {
    Map<String,Object> getUserPrefences();
}

然后你可以让你的类实现该接口,例如:

public class Login implements UserPreferenceProvider {
    ...
    public class Class1 implements UserPreferenceProvider {
        ...
        public class Class2 implements UserPreferenceProvider {
            ...
        }
    }
}

他们的getUserPreferences()实现返回要写入的首选项。

然后,您可以更改addUserPreferences()以获取UserPreferenceProvider,当您遍历字段时,请检查是否找到了UserPreferenceProvider,如果是,请将其投射到该字段并传递给它到addUserPreferences()

这也可以更准确地表达您的意图。我相信这里的根本问题是你有这些任意对象,你正在尝试使用它们,虽然从概念上讲它们有一些共同之处,但你的代码并没有代表这个概念;我知道这有点模糊,但由于没有让你的代码反映出来,你现在面临着一个尴尬的任务,就是必须找到一种方法来强制你的任意对象以一种常见的方式对待。


第二个选项可以是创建自定义注释,例如@UserPreference,并使用它来标记您要编写的字段。然后,您可以遍历字段,当您找到带有此批注的字段时,将其单个键/值添加到用户首选项(即,对字段本身进行操作,而不是将整个容器类传递给{{1 }})。

这可能比您设计的第一个选项更合适也可能不合适。它的优点是不会强迫您使用这些接口,也不必编写代码将数据打包到地图或addUserPreferences()的任何内容中;它还为您提供了对导出哪些属性的更精细控制 - 实际上这会将您的焦点从对象转移到单个属性本身。使用最少的代码,这将是一个非常干净的方法。

如果你已经有豆式吸气剂,那么使这种方法更方便的一种可能方法是使用例如Apache BeanUtils获取值而不是滚动自己的值;但对于你的情况来说,它是一种非常基本的反射,可能不值得额外的依赖。


以下是获取使用自定义注释标记的对象的字段名称和值的示例。第二个注释用于标记包含应递归下降和扫描的对象的字段。这很简单:

getUserPreferences()

输出结果为:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

// @UserPreference marks a field that should be exported.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface UserPreference {
}

// @HasUserPreferences marks a field that should be recursively scanned.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface HasUserPreferences {
}


// Your example Login class, with added annotations.
class Login {

    @UserPreference public String token;      // <= a preference
    @UserPreference public String customerid; // <= a preference
    @HasUserPreferences public Class1 class1; // <= contains preferences

    public class Class1 {
        @HasUserPreferences public Class2 class2; // <= contains preferences
        @UserPreference public String string1;    // <= a preference

        public class Class2 {
                public int int1; // <= not a preference
                @UserPreference public String string2; // <= a preference
                @UserPreference public String string3; // <= a preference
        }
    }

    // Construct example:
    public Login () {
        token = "token1";
        customerid = "586969";
        class1 = new Class1();
        class1.string1 = "string1Value";
        class1.class2 = class1.new Class2();
        class1.class2.string2 = "string2Value";
        class1.class2.string3 = "string3Value";
    }

}


public class ValueScanExample {

    // Recursively print user preferences. 
    // Fields tagged with @UserPreference are printed.    
    // Fields tagged with @HasUserPreferences are recursively scanned.
    static void printUserPreferences (Object obj) throws Exception {
        for (Field field : obj.getClass().getDeclaredFields()) { 
            // Is it a @UserPreference?
            if (field.getAnnotation(UserPreference.class) != null) {
                String name = field.getName();
                Class<?> type = field.getType();
                Object value = field.get(obj);
                System.out.println(name + " - " + type + " - " + value);
            }
            // Is it tagged with @HasUserPreferences?
            if (field.getAnnotation(HasUserPreferences.class) != null) {
                printUserPreferences(field.get(obj)); // <= note: no casts
            }
        }
    }

    public static void main (String[] args) throws Exception {
        printUserPreferences(new Login());
    }

}

请注意&#34; int1&#34;输出中不存在,因为它没有标记。你可以run the example on ideone

仍然可以找到原始的基本注释示例here

顺便说一句,您可以使用注释做各种有趣的事情,例如:添加可选参数,允许您覆盖首选项中的字段名称,添加一个允许您指定自定义对象的参数 - &gt;用户首选项字符串转换器等

答案 1 :(得分:0)

我已经找到了一种简单的方法来做到这一点。任何有建议使其更好或有代码问题的人请评论。下面的代码对我有用

    try {
        Class<?> objClass = obj.getClass();
        List<Object> subObjectList = new ArrayList<Object>();
        // Loop over all the fields and add the info for each field
        for (Field field: objClass.getDeclaredFields()) {
            if(!field.isSynthetic()){
                if(isWrapperType(field.getType())){
                    System.out.println("Name: " + field.getName() + " Value: " + field.get(obj));
                }
                else{
                    if(field.getType().isArray()){
                        Object[] fieldArray = (Object[]) field.get(obj);
                        for(int i = 0; i < fieldArray.length; i++){
                            subObjectList.add(fieldArray[i]);
                        }
                    }
                    else{
                        subObjectList.add(field.get(obj));
                    }
                }
            }
        }

        for(Object subObj: subObjectList){
            printObjectFields(subObj);
        }
    }catch(IllegalArgumentException e){
        // TODO Auto-generated catch block
        e.getLocalizedMessage();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.getLocalizedMessage();
    }

isWrapperType来自我在this堆栈溢出问题中找到的代码。我所做的只是将Stringint添加到集合中。