Reputation: 253
Im trying to make a method that creates a new object of a class, but I want to be able to make objects of many different classes, so making a method for each class won't work for me. Is there any way I can pass in a class to a method, so that a new object can be created? All of my classes have the same constructor.
Upvotes: 1
Views: 7895
Reputation: 1372
package com.loknath.lab;
public class HasHash {
public static void main(String[] args) throws Exception {
HasHash h = createInstance(HasHash.class); h.display();
} //return the instance of Class of @parameter
public static T createInstance(Class className) throws Exception { return className.newInstance(); }
private void display() { System.out.println("Disply "); }
}
Upvotes: 0
Reputation: 48837
You could use
public <T> T instanciate(Class<? extends T> clazz) throws Exception {
return clazz.newInstance();
}
and call it like
MyObject o = instanciate(MyObject.class);
If you do it that way, the classes you want to instanciate must have a default constructor with no argument. Otherwise, you'll catch a java.lang.InstantiationException
.
Upvotes: 8
Reputation: 722
I believe that you are looking for reflection.
Check out this question: What is reflection and why is it useful?
Upvotes: 0
Reputation: 3503
You can use reflection to switch
on a type name and do what you gotta do.
Upvotes: 0
Reputation: 5399
Have you read about Abstract Factory pattern?
EDITED
BTW, I do not think that reflection is good way to make your architecture, if you have a lot of classes with the same constructor try to use useful patters like Factory or Builder instead of creating one method with reflection.
Upvotes: 1