简体   繁体   中英

Java Generics - Compile time validation of type and implementing object

I have a method to add implementing class' objects against interface class and I want to make this as a generic one. The implementing class also extends a class X

public abstract class X<T>{...}

public interface InterfaceA{...}

public class A extends X implements InterfaceA{...}

now, currently my method is:

public <S, <T extends X<S>> void add(Class<S> clazz, T object){...}

But I have no use of type parameter on X, it is just for the above method. Is there a way I could have X without type parameter and still have compile-time validation in method 'add' please?

Thanks

EDIT:

I think my question is not clear. Please look at the below example code:

public interface I {}

public abstract class X {}

public class A extends X implements I {}

public class B implements I {}

public class C extends X {}

public class Main {
    public static void main(String[] args) {
        add(I.class, new A());  // uses first method
        add(I.class, new B());  // uses second method
        add(I.class, new C());  // uses first method
    }

    public static <P, T extends P> void add(Class<P> c, T object) {}  //No

    public static <P, T extends X> void add(Class<P> c, T object) {}  //No

}

I need an 'add' method that just accepts A's instance and not B's not C's. Both the above method signature don't fulfill my requirement

If you don't care about the type parameter of X , just make it Object :

public class A extends X<Object> implements InterfaceA{...}

So the method will work with anything.

I believe you can remove the type on X and still get a compile-time error for add in the following manner. Now, of course, a little more context will be more helpful if this doesn't meet your requirement.

public abstract class X {
}

public class A<T> extends X implements InterfaceA {

      public <S, M extends X> void add(Class<S> clazz, M object){
      }

      public void abc() {
         Class<String> clazz = String.class;
         this.add(clazz, new B());//This should throw compilation error
      }

}

public class B implements InterfaceA {
}

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