简体   繁体   中英

Generic type in class declaration

I have

1) a basic interface,

2) a few classes that implement this interface,

3) and a generic class that I want to accept, as a parameter, any of the implementing classes

I have tried the following:

public class Foo extends Bar<? extends SomeInterface> {

    public Foo(List<? extends SomeInterface> someInterfaceList) {
        super(someInterfaceList);
    }

    ...
}

I receive the error No Wildcard Expected . Elsewhere in my code I have statements such as List<? extends SomeInterface> List<? extends SomeInterface> and I receive no errors, so why am I running into problems here? How can I fix this problem and still get the desired results?

I have tried search 'No Wildcard Expected' and 'wildcard in class declaration' to no avail. Thanks in advance!

It sounds like you want to declare a generic type argument that you will reference elsewhere. Wildcards only make sense when the type is used only once, and when declaring a generic type parameter for a class this doesn't make any sense.

Try this instead:

public class Foo<T extends SomeInterface> extends Bar<T> {

    public Foo(List<T> someInterfaceList) {
        super(someInterfaceList);
    }

    ...
}

As your code was written, there was no way for the user of your class to specify the generic type argument for Bar<> , since Foo wasn't itself a generic type.

Further, if this were possible, it would have been possible for the generic argument to Bar<> to be different than the generic argument to List<> -- as long as both types implemented SomeInterface there would not be a compile-time issue with these definitions, but there could have been a much more confusing error message later when you incorrectly assumed that both types must be the same.

So, declare the generic type once as a generic argument to the Foo class, and then use that type ( T in my example) elsewhere to refer to that type instead of accepting some new generic type argument that may not refer to the same type.

I'm not exactly sure what you're looking for, so it might help if you could provide a little more detail. Perhaps you could be a little more specific about how you're planning to instantiate and use these objects?

Anyways, I think you might be looking for something like this:

import java.util.List;

public class Foo<T extends SomeInterface> {
  public Foo(List<T> someInterfaceList) {
    for (T item : someInterfaceList) {
      // do something with each item
    }
  }
}

class Bar<T> {}

interface SomeInterface<T> {
  T x(T y);
}

Or, alternatively, you could just use the following for the constructor:

public Foo(List someInterfaceList) {

but you wouldn't have an easy way of getting the type T of the items in the list.

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