首页 > 解决方案 > 从不同对象获取值的通用方法,无需通用超类型

问题描述

我正在使用一个开放的 API(所以不能更改他们这边的代码),它提供了一个枚举值类型的数组。

User.IDType.values(); 

问题在于上述数组中的每种类型。我必须调用一个 value() 函数来为提供的类型返回一个字符串值数组。

public static String[] enumValues(IDType[] types) {
        String[] values = new String[types.length];
        for ( int i=0; i < types.length; i++ ) {
            values[i] = types[i].value();
        }

        return values;
    }

为了避免为每种类型编写此函数,我想编写如下所示的泛型方法,但问题是:如何调用泛型类型的函数值?

static <T> String[] enumValues(T[] types)
    {
        String[] values = new String[types.length];
        for (int i=0; i<types.length; i++) {
            values[i] = types[i].value;
        }

        return values;
    }

注意:任何类型都没有超类 ex: Type,我可以使用它。

标签: javagenerics

解决方案


由于您有以下限制:

任何类型都没有超类 ex: Type,我可以使用它。

剩下的解决方案是使用反射 API。但是,这样的解决方案不是类型安全的,运行时错误,而不是在 Enum 中更改方法时会抛出编译时错误。value以下是使用反射 API 的示例。

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class GenericEnumTest {
    static <T> String[] enumValues(T[] types) {
        String[] values = new String[types.length];
        for (int i = 0; i < types.length; i++) {
            Method valueMethod;
            try {
                valueMethod = types[i].getClass().getMethod("value");
                values[i] = (String) valueMethod.invoke(types[i]);
            } catch (NoSuchMethodException | SecurityException | IllegalArgumentException | IllegalAccessException
                    | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
        return values;
    }

    public static void main(String[] args) {
        String[] result = enumValues(new IDType[] { IDType.TEST1, IDType.TEST2 });
        System.out.println(Arrays.toString(result));
    }

    public static enum IDType {
        TEST1("test1"), TEST2("test2");

        private IDType(String value) {
            this.value = value;
        }

        private String value;

        public String value() {
            return value;
        }
    }
}

参考:Java Doc Class.getMethod()
Java Doc Method 类


推荐阅读