munHunger
munHunger

Reputation: 2999

Using type parameter as method input

I have a problem with sending down Type parameters from one method to another. It is probably best to illustrate with code...

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;
    }
}

I have no idea of how to get the type parameters from a into b. In that code example, I am getting

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

Probably should not use GenericType at all, but I don't know how else to do it

Upvotes: 2

Views: 696

Answers (1)

Eran
Eran

Reputation: 393771

Have you considered moving the type parameters to the class level?

This way you don't have to "send down Type parameters from one method to another".

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;
    }
}

Upvotes: 2

Related Questions