tm1701
tm1701

Reputation: 7591

Java - How can I create a class that can process objects of Generics of a specific [restricted] type?

How can I create a class that can process objects of Generics of a specific type?

For example, I have this class based on Generics:

interface TypeWithGetAndSetMethod<T> {
    void storeLocal(T arg1);
    T getLocal();
}

class RestrictedClassType<T> implements TypeWithGetAndSetMethod<T> {
    T local;
    public void storeLocal(T arg1) {
        local = arg1;
    }
    public T getLocal() {
        return local;
    }
}

A simple test succeeds:

void testRestrictedGenericsType() {
    RestrictedClassType<String> restrictedClassType = new RestrictedClassType<>();
    restrictedClassType.storeLocal( "String-1");
    System.out.println( "Restricted class: " + restrictedClassType.getLocal());
}

Now I would like to have a class than can process the above (generic) class. So I pass it to a processing class and the method can only accept generic classes implementing the interface.

The code I have so far is not compiling:

// Not compiling
class ProcessRestrictedGenericsType<T> {
    T localVar;
    public <S extends TypeWithGetAndSetMethod<T>> void procesTypeWithGetAndSetMethod(T arg) {
        this.localVar = arg;
    }
    public T getRestrictedType() {
        return localVar.getLocal();
    }
}

The test of that processing code has compiling code:

void testMethodWithRestrictedGenericType() {
    RestrictedClassType<String> restrictedClassType = new RestrictedClassType<>();
    restrictedClassType.storeLocal( "String-1");
    ProcessRestrictedGenericsType<TypeWithGetAndSetMethod> classRestrictedMethod = new ProcessRestrictedGenericsType<>();
    classRestrictedMethod.aMethodWithRestrictedGenericType( restrictedClassType);
    System.out.println( "The output is: " + classRestrictedMethod.getRestrictedType());
}

Can you help me creating the processing class?

Upvotes: 0

Views: 35

Answers (1)

Andrew Vershinin
Andrew Vershinin

Reputation: 1968

You need both parameters, the value type and the wrapper type:

class ProcessRestrictedGenericsType<T, W extends TypeWithGetAndSetMethod<? extends Value>> {
    WlocalVar;
    public void procesTypeWithGetAndSetMethod(Warg) {
        this.localVar = arg;
    }
    public T getRestrictedType() {
        return localVar.getLocal();
    }
}

Then your test will work:

void testMethodWithRestrictedGenericType() {
    RestrictedClassType<String> restrictedClassType = new RestrictedClassType<>();
    restrictedClassType.storeLocal( "String-1");
    ProcessRestrictedGenericsType<String, TypeWithGetAndSetMethod<String>> classRestrictedMethod = new ProcessRestrictedGenericsType<>();
    classRestrictedMethod.procesTypeWithGetAndSetMethod(restrictedClassType);
    System.out.println( "The output is: " + classRestrictedMethod.getRestrictedType());
}

Upvotes: 1

Related Questions