Reputation: 551
This seems to be very easy, but I was not able to solve it for days now... I must be too stupid, and so I hope to get some help here (couldn't find the answer though).
I simply want to know if a given Type implements some interface. For example, does type X implement the Serializable
interface? It should give true
for types X like JComponent.class
, and false for Thread.class
.
Or, stated differently, can an object of type X be cast to the given interface?
I tried instanceof
and isAssignableFrom
, but nothing seems to work.
EDIT:
Ok, maybe I really was too stupid :-( I have tried the following:
This code does not compile:
Type t1 = JComponent.class;
Type t2 = Thread.class;
Serializable.class.isAssignableFrom(t1);
Serializable.class.isAssignableFrom(t2);
This code yields true for both t1 and t2 (which makes sense, of course):
Type t1 = JComponent.class;
Type t2 = Thread.class;
Serializable.class.isAssignableFrom(t1.getClass());
Serializable.class.isAssignableFrom(t2.getClass());
(And similar things with instanceOf do not work either.)
But what DOES seem to work is this:
Type t1 = JComponent.class;
Type t2 = Thread.class;
Serializable.class.isAssignableFrom((Class<?>) t1);
Serializable.class.isAssignableFrom((Class<?>) t2);
As a Type that implements an interface should always be a Class (right?), the cast should work in all cases... (EDIT: There is an even simpler solution - I used the wrong method for retreiving the constructor parameters (getGenericParameterTypes); using just getParameterTypes gives a list of Class objects rather than Type objects and there is no problem at all.)
Thank you for the very quick help!
Lukas
Upvotes: 0
Views: 778
Reputation: 115328
No, both instanceof
and isAssignablefrom()
work. Try the following example:
List<String> list = new ArrayList<>(); // it is serializable
System.out.println(list instanceof Serializable); // should print true
System.out.println(Serializable.class.isAssignableFrom(list.getClass())); // should print true too
EDIT
Concerning to the second question. Yes, you can use both techniques to check whether the object can be cast.
Upvotes: 2