Home > Enterprise >  Java type for any class that implements an interface
Java type for any class that implements an interface

Time:01-31

We have:

  intercace ISomething { ... }
  class A implements ISomething { ... }
  class B extends A { ... }

Would like to have a type for all classes that implement ISomething, so that:

  Class<ISomething> klass;
  klass = new A.class;
  klass = new B.class;

are all valid. The code as-is doesn't compile. What can I use to replace the type Class<ISomething>?

CodePudding user response:

Class<? extends ISomething> clazz = B.class;
clazz = A.class;
clazz = ISomething.class;
// all valid

CodePudding user response:

There is no need to use Class , like generic class IsSomething, It is completely wrong until you made another class like

   Class<T extends IsSomething>.

But in java, you can give the object reference of class to the interface or super class that implements or extends that respectively. Just like, you direct use this code,

  IsSomething klass;
  klass = new A.class;
  klass = new B.class;

I hope this will solve your question.

  •  Tags:  
  • java
  • Related