| Author |
how to know if one is extends other's class
|
david dabush
Greenhorn
Joined: Sep 16, 2012
Posts: 10
|
|
i have two objects and i want to know if one object is extends or implements the other object class or interface.
how do i do it?
|
 |
Kemal Sokolovic
Bartender
Joined: Jun 19, 2010
Posts: 792
|
|
You might want to look at isAssignableFrom method.
Here is an example:
Edit: Note that you can use the same method to check if a class implements an interface, as noted in the API.
|
The quieter you are, the more you are able to hear.
|
 |
david dabush
Greenhorn
Joined: Sep 16, 2012
Posts: 10
|
|
o.k
thank you its working
|
 |
Kemal Sokolovic
Bartender
Joined: Jun 19, 2010
Posts: 792
|
|
Even for objects of classes that you declare, you can use the same method to check if one extends another, or if one implements interface. Just instead class name use subInstance.getClass(), everything else is the same.
You can also use getSuperclass() method to see if your class or instance of it extends from another class, and getInterfaces() to list all the interfaces your class implements.
Edit: You changed your response in the meantime, so now I see the first answer is suitable for you.
|
 |
david dabush
Greenhorn
Joined: Sep 16, 2012
Posts: 10
|
|
i have to classes names as strings.
and i want to know if one class extends or implements the othe class;
exapme:
String class1Name, class2Name;
how to know if class class1Name extends or implements class2Name?
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4732
|
|
david dabush wrote:thank you its working
Maybe it is, but have you asked yourself: Why do I need to know this?
It smacks to me of reflection which, as far as I'm concerned, is either
(a) a last resort
or
(b) suggests bad design
Java is staticallly-typed and reflection is an aberration. Use it at your peril.
You have been warned.
Winston
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
Kemal Sokolovic
Bartender
Joined: Jun 19, 2010
Posts: 792
|
|
david dabush wrote:i have to classes names as strings.
and i want to know if one class extends or implements the othe class;
exapme:
String class1Name, class2Name;
how to know if class class1Name extends or implements class2Name?
In that case check forName method of Class class.
|
 |
david dabush
Greenhorn
Joined: Sep 16, 2012
Posts: 10
|
|
and how i use reflection so i can turn strings into class?
can you give example?
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32599
|
|
You don’t need reflection.
And here are two ways of getting a Class object from its name rather than from an instance:-Count the compiler errors before running that code.
|
 |
Kemal Sokolovic
Bartender
Joined: Jun 19, 2010
Posts: 792
|
|
Did you even try to read the API that I pointed you to at the beginning? This is one way to do it:
|
 |
 |
|
|
subject: how to know if one is extends other's class
|
|
|