简体   繁体   中英

Returning a new instance of a generic type, where T is set to the type of a given arg

I have a question regarding methods that can return parameterized generic types in Java. Bear with me as I probably won't explain it concisely! Say we have the following:

public class SomeClass<T extends AnotherType> extends SomeSuperClass<T>{
    private AnotherType member;        

    public SomeClass(AnotherType at){
       member = at;
    }

    public SomeSuperClass<xxx> foo(AnotherType bar){
       return new SomeSuperClass<xxx>(bar);
    }

}

So we have this trivial factory-like method 'foo'. What can I put in place of 'xxx' to represent that the parameterized type of the returned new instance will be the specific type of the 'bar' object. eg if bar was of class Bar (a subclass of AnotherType), then we would return an instance of SomeSuperClass<Bar>(bar)

I know I could use '?' to stand for any type and have:

return new SomeSuperClass<?>(bar);

But I was hoping to be more specific such that:

return new SomeSuperClass<bar.class>(bar);

I cant use T, incase bar's type is higher in the SomeSuperClass hierarchy? Also using just SomeClass<AnotherType> is too vague again.

What is the syntax to use in this situation?

How about this?

public <U extends AnotherType> SomeSuperClass<U> foo(U bar){
    return new SomeSuperClass<U>(bar);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM