Can we use generic to allow only specific types instead of any type ?

后端 未结 3 951
庸人自扰
庸人自扰 2021-01-22 19:49

Suppose I have three isolated public classes (no IS-A relationship) A, B and C. I want to define a field in C such that it\'s type can either be A or B.

Currently I\'m a

相关标签:
3条回答
  • 2021-01-22 20:38

    You can't do that but you can set boundaries on what type you want to accept.

    If you have

    class A extends BaseType {}
    class B extends BaseType {}
    

    you can define the class C to be

    class C<T extends BaseType> { ... }
    

    Either a class or an interface as base type work.

    0 讨论(0)
  • 2021-01-22 20:43

    Make the constructor private:

    private C(T param){
    

    And then provide static factory methods to create instances of particular types:

    public static <T extends A> C<T> create(T param) {
      return new C<>(param);
    }
    
    public static <T extends B> C<T> create(T param) {
      return new C<>(param);
    }
    

    This doesn't prevent you from using the type C<SomeOtherType>; you just can't create an instance of it.

    0 讨论(0)
  • 2021-01-22 20:44

    You could use a marker interface for that:

    interface AllowedInC {
        // intentionally empty because it will be used as a mere marker
    }
    
    class A implements AllowedInC {
        ...
    }
    
    class B implements AllowedInC {
        ...
    }
    
    class C<T extends AllowedInC> {
       ...
    }
    

    Only classes A or B (or another class implementing AllowedInC) will be useable in C<T>.

    0 讨论(0)
提交回复
热议问题