Source From Here
Question
I'm playing around with Java's reflection API and trying to handle some fields. Now I'm stuck with identifying the type of my fields. Strings are easy, just domyField.getType().equals(String.class). The same applies for other non-derived classes. But how do I check derived classes? E.g. LinkedList as subclass ofList. I can't find any isSubclassOf(...) or extends(...) method. Do I need to walk through all getSuperClass() and find my supeclass by my own?
How-To
You want this method:
From the
JavaDoc:
Sample Code
Below groovy sample code will demonstrate how to check if you can assign one object to other class's object (Parent class can point to child class):
Execution result:
If you switch the clause of A and B class to:
The result will be different! (
Because class A is parent of class B!)
Question
I'm playing around with Java's reflection API and trying to handle some fields. Now I'm stuck with identifying the type of my fields. Strings are easy, just domyField.getType().equals(String.class). The same applies for other non-derived classes. But how do I check derived classes? E.g. LinkedList as subclass ofList. I can't find any isSubclassOf(...) or extends(...) method. Do I need to walk through all getSuperClass() and find my supeclass by my own?
How-To
You want this method:
- boolean isList = List.class.isAssignableFrom(myClass);
Sample Code
Below groovy sample code will demonstrate how to check if you can assign one object to other class's object (Parent class can point to child class):
- class A {
- @Override
- public String toString(){return "A's object"}
- }
- class B extends A{
- @Override
- public String toString(){return "B's object"}
- }
- class C {
- @Override
- public String toString(){return "C's object"}
- }
- objlist = []
- objlist << A.class.newInstance()
- objlist << B.class.newInstance()
- objlist << C.class.newInstance()
- objlist.each{ obj->
- if(B.class.isAssignableFrom(obj.class))
- {
- // obj can be assigned to B
- B o = (B)obj
- printf("I am %s assigned to B\n", o)
- }
- else if(A.class.isAssignableFrom(obj.class))
- {
- // obj can be assigned to A
- A o = (A)obj
- printf("I am %s assigned to A\n", o)
- }
- else
- {
- printf("I am %s\n", obj)
- }
- }
If you switch the clause of A and B class to:
- ...
- if(A.class.isAssignableFrom(obj.class))
- {
- // obj can be assigned to A
- A o = (A)obj
- printf("I am %s assigned to A\n", o)
- }
- else if(B.class.isAssignableFrom(obj.class))
- {
- // obj can be assigned to B
- B o = (B)obj
- printf("I am %s assigned to B\n", o)
- }
- else
- {
- printf("I am %s\n", obj)
- }
- ...
This message was edited 7 times. Last update was at 26/11/2014 11:39:33
沒有留言:
張貼留言