Link to home
Start Free TrialLog in
Avatar of ctangent
ctangent

asked on

Java Reflection getting name of concrete class/subclass that implements an abstract class.

Can I use reflection to get the name of the class that is implementing an abstract class in a situation like this:

MyAbstractClass c = new MyConcreteImpl();
Use reflection on c to get "MyConcreteImpl()".
Or better yet, use reflection to get a concrete version of MyConcreteImpl() that I could pass onto another function as an argument, so it would be the same as:

MyConcreteImpl c = new MyConcreteImpl();
myfunction(c)


In other words, to start with:
MyAbstractClass c = new MyConcreteImpl();

but before I get to "myfunction", use reflection to somehow find out the subclass that is being used and send this off to myfunction.


:-)  Did I confuse anybody?

ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
getClass() retruns the class the the instanbce, not the class of the variable declaration.
Avatar of mukundha_expert
mukundha_expert

>>but before I get to "myfunction", use reflection to somehow find out the subclass that is being used and send this >>off to myfunction.

you can do that either using reflection or using instanceof operator


like,

if ( c instanceof  MyConcreteImpl )
 call the method,

or if ( c.getClass().getName().equals ( "MyConcreteImpl" )

 call the method,

i would prefer the instanceof operator


 
use getClass() to figure out the class of variable c (as suggested by objects). So, in the cases where c is MyConcreteImpl, it would return class indicating MyConcreteImpl