• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2263
  • Last Modified:

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?

0
ctangent
Asked:
ctangent
  • 2
1 Solution
 
objectsCommented:
yes:

Class clazz = c.getClass();
String name = clazz.getName();
0
 
objectsCommented:
getClass() retruns the class the the instanbce, not the class of the variable declaration.
0
 
mukundha_expertCommented:
>>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


 
0
 
Ajay-SinghCommented:
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
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now