get Class

G

Guest

Can I get the Class of a class, without create an instance of that class?

-----------
class MyClass {
}

class A {
public static int main(String[] argv) {
MyClass mc = new MyClass();
Class cls = mc.getClass();
// I want something like:
// Class cls = MyClass.getClass();
Object obj = createAnInstanceOfAnyClass(cls);
}

public Object createAnInstanceOfAnyClass (Class cls) {
return cls.newInstance();
}
}
 
H

hal

Can I get the Class of a class, without create an instance of that class?

You should be able to do this.
Instead of object.getClass();
use the Class.forName(String name_of_class);

// I want something like:
// Class cls = MyClass.getClass();
Object obj = createAnInstanceOfAnyClass(cls);
}

public Object createAnInstanceOfAnyClass (Class cls) {
return cls.newInstance();
}
}

By the way - your createAnInstanceOfAnyClass method will fail if the is
no empty Constructor is found in the Class - so you might want to make a
new instance upon a suitable Constructor from the Class instead.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top