• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2256
  • 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();

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?

  • 2
1 Solution

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


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
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

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