Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member type with multiple bounds

Tags:

java

generics

So I just learned that I can

public <T extends SomeClass & SomeInterface<OtherClass>> doSomething(T foo);

in Java to express that foo extends SomeClass and also implements SomeInterface<OtherClass>. So far, so good.

But how would I assign foo in doSomething() to a member variable? The class of course does not know anything of the type definition that is attached to the doSomething() method.

The context where I need this is a POJO whose constructor needs to be argumented with said T and that needs to return the said T again.

The closest I came was the following:

public class ThisClass implements AnotherInterface<AnotherClass> {

    private final Object obj;

    public <U extends SomeClass & SomeInterface<AnotherClass>> ThisClass(U obj) {
        this.obj = obj;
    }

    public <U extends SomeClass & SomeInterface<AnotherClass>> U getObject() {
        return (U) obj;
    }
}

but I'm unable to wind my head around to get a solution without the unchecked cast.

like image 586
Thomas Keller Avatar asked Jun 10 '26 00:06

Thomas Keller


1 Answers

Can't you make the class generic:

public class ThisClass<U extends SomeClass & SomeInterface<AnotherClass>>
                                   implements AnotherInterface<AnotherClass> {

    private final U obj;

    public ThisClass(U obj) {
        this.obj = obj;
    }

    public U getObject() {
        return obj;
    }
}

and use it like this:

ThisClass<String> instance = new ThisClass<>("Foo");
String value = instance.getObject();
like image 65
jlordo Avatar answered Jun 12 '26 14:06

jlordo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!