Reputation: 8841
I know how to check if an object implements an interface. But how do I check in the parent class if the subclass implements the interface?
Suppose
class A {
//What can I do to check here?
}
and
class B extends A implements Listener{
}
and
class C extends A {
}
Here B
implements the interface Listener
but C
does not. How do I check it?
Upvotes: 2
Views: 1870
Reputation: 131346
this
or Object.getClass()
returns the reference respectivly the Class object at runtime.
So you can use them to check whether the object or the class implements a specific interface.
If you manipulate classes :
if (Listener.class.isAssignableFrom(C.class)){
...
}
If you manipulate instances :
if (this instanceof Listener){
...
}
Upvotes: 5
Reputation: 26
What I can think of right now is creating an object of that class and checking with
object instanceof interface
Or
object.getClass().getInterfaces()
Upvotes: 0
Reputation: 308021
You can just have a method like this in A
:
public void maybeAddListener() {
if (this instanceof Listener) {
somethingOrAnother.addListener((Listener) this);
}
}
Whether or not that's a good idea depends on what exactly you want to achieve with this. If subclasses of A
are likely to implement Listener
then a better idea is to just implement it in A
with a do-nothing implementation and let subclasses override the appropriate methods.
Upvotes: 1
Reputation: 19926
You can check in the parent class if the this
variable implements your Listener
-interface, because the this
-variable references to the actual subclass object:
public class A{
public void doSomething(){
if(this instanceof Listener){
// do something if it is a listener
}
}
}
So above code block will be executed for the subclass B
but not for C
Upvotes: 2