java泛型对象的泛型类

时间:2017-12-01 13:49:42

标签: java

我遇到这种情况:

我从JSon文件收到一个字符串,并将其解析为一个列表,所以最后我有一个 myObject 的列表

我想创建一个通用方法来搜索此列表中的一个东西。我想创建一个方法,该方法具有参数一般对象列表和该对象的类型,在列表扫描期间,将此通用对象转换为传递的类型。

List<Mission_queue> queue = gson.fromJson((String)response.get(1),listType);
Utility.CheckProperty(queue, Mission_queue.class, paramName, paramSearch);

我的实用程序方法

public static Boolean CheckProperty(List<?> list, Class<?> classType, String propertyName, String propertyValue) {
    int idx = 0;
    for (Iterator<?> it = list.iterator(); it.hasNext(); idx++) {
        Object obj = it.next();
        // here I want cast my generic Obj from Object to ClassType
    }
    return false;
}

那么,我该如何演员?我会创建一个通用方法,因为我会有很多不同的列表,但每次我需要搜索内部的东西。

你有什么想法吗?

非常感谢

3 个答案:

答案 0 :(得分:0)

Theres没有理由作为类的类型进行转换,因为你事先不知道编写代码的类的方法,如果你使用了一个接口,你可能会这样做,但是因为你接收的是String属性名,我认为你真的想做:

public static Boolean checkProperty(List<?> list, Class<?> classType, String propertyName, String propertyValue) {
    int idx = 0;
    // IMPORTANT: Do lookup before the loop to avoid loose of performance
    Field propertyAccessor = classType.getDeclaredType(propertyName);
    try {
        propertyAcessor.setAcessible(true);
    } catch(Throwable e) { e.printStackTrace(); }

    for (Iterator<?> it = list.iterator(); it.hasNext(); idx++) {
        Object obj = it.next();
        String propertyFromInsideObject = (String) propertyAcessor.get(obj);
        //Here you can use the variable that is the field you want to get
    }
    return false;
}

答案 1 :(得分:0)

此解决方案可能存在性能缺点,但不需要接收任何类类型。

public static <T> Boolean CheckProperty(List<T> list, String propertyName, String propertyValue) {
    for (T object : list) {
        // Here you have an object of type T
        try {
            Field field = object.getClass().getDeclaredField(propertyName);
            field.setAccessible(true);
            String value = (String) field.get(object);

            // Use the value here
            if (propertyValue.equals(value)) {
                // TODO
            }

        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    return false;
}

答案 2 :(得分:0)

我认为obj.getClass().isAssignableFrom(classType)classType.cast(obj)具有正确的异常处理功能是您正在寻找的。

但是......如果我理解正确,您想要按给定的propertyName和预期/可接受的propertyValue检查属性值?这是对的吗?

如果是这样,也许你不需要投射任何东西而只是使用反射? 获得一个值有两种方法:

  • 简单方法:使用org.apache.commons.beanutils.BeanUtils.BeanUtils.getProperty(Object bean, String name) - 您的对象必须具有符合Java Beans规范的getter。

  • 另一种方式:使用自己的代码进行反射,如@ marcos-vasconcelos建议的那样。我想做更多的工作。

相关问题