Skip to main content

Help kindly requested

2 replies [Last post]
Joined: 2009-05-31

Is there a way in Java that I can determine the type class of an Object returned by the loadClass() method of a ClassLoader. The reason for this is I need to cast the returned Object dynamically to its type without needing to hard-code it first because at some situations, you'd never know what type of class you'd be dealing with.

Below is an example situation:

ClassLoader classLoader = this.getClass().getClassLoader();
Class anyClass = classLoader.loadClass("aymanClass");

// the following line is where I need to know the type 'aymanClass' dynamically instead of hard-coding it as it's shown below:

Object x = (aymanClass) anyClass.newInstance();

//I was dreaming of something like this:

Type t = anyClass.getType();
Object x = (t) anyClass.newInstance();

I don't know if there's something similar in Java or just a work-around?

Thanks and regards,


Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2009-11-04

Use the Object getClass() method to get a Class object
Every class has the class Object as an ancestor. A reflection method in the Object class is getClass(), which returns the Class of that object.
Class methods
java.lang.Class has two useful methods: getName() for getting a string name of the class and getSuperclass() for getting the Class object of the parent class, or null if this is the Object class. For example,
String s = "abc";
Class cls;
cls = s.getClass(); // Represents the String class.
System.out.println(cls.getName()); // Prints "java.lang.String"

Joined: 2009-05-31

Hi and thank you for your reply. What you explained is OK with me. The problem is I need a way to dynamcially cast classes at run time.

Suppose you have several classes implementing an interface called 'Vehicle' and you want at runtime to know the implementing class whether it is a pickup class or a sedan class and cast your dynamic object to it accordingly. How would you accomplish that in Java?