使用type参数作为方法输入

时间:2018-01-15 09:28:21

标签: java generics

我将Type参数从一种方法发送到另一种方法时遇到问题。 最好用代码说明......

import javax.ws.rs.core.GenericType;
public class Test {

    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        new Test().a(() -> "ABC");
        new Test().a(() -> 42);
        new Test().a(() -> Boolean.TRUE);
    }

    public <T, E extends Exception> T a(UpdateFunction<T, E> function) throws InstantiationException, IllegalAccessException, E {
        Data<T,E> data = b(new GenericType<T>(){}, new GenericType<E>(){});
        data.data = function.update();
        //TBI: save and process data here
        return data.data;
    }

    public <T, E extends Exception> Data<T, E> b(GenericType<T> type, GenericType<E> exception) throws IllegalAccessException, InstantiationException {
        return new Data<T, E>(); //In the real life scenario this takes a lot of code
    }

    public class Data <T, E extends Exception> {
        T data;
    }

    @FunctionalInterface
    public interface UpdateFunction <T, E extends Exception>{
        T update() throws E;
    }
}

我不知道如何将a的类型参数转换为b。 在那个代码示例中,我正在

IllegalArgumentException: javax.ws.rs.core.GenericType<T> does not specify the type parameter T of GenericType<T>

可能根本不应该使用GenericType,但我不知道如何做到这一点

1 个答案:

答案 0 :(得分:2)

您是否考虑过将类型参数移到班级?

这样您就不必“将类型参数从一种方法发送到另一种方法”。

class Test<T, E extends Exception> {

    public static void main(String[] args) {
        new Test().a(() -> "ABC");
    }

    public void a(UpdateFunction<T, E> function) {
        b();
    }

    public Data b() {
        return new Data();
    }

    public class Data { // Data class has access to T and E
        E e;
        T t;
    }

    @FunctionalInterface
    public interface UpdateFunction <T, E extends Exception>{
        T update() throws E;
    }
}
相关问题