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.
6 Answers
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.
 
    
    - 47,968
- 31
- 142
- 252
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.
 
    
    - 5,389
- 5
- 28
- 45
- 
                    Thanks! I didn't understand most of it because im new to programming, but I understood enough to know what to do, and my code works! – Lolmister Jun 14 '12 at 21:22
- 
                    And it is a problem, try to ask some skilled(local) java programmer to help you to create design, because answer of sp00m will help you, but it is not a GOOD idea, but it up to you. – Sergii Zagriichuk Jun 14 '12 at 21:27
You can use reflection to switch on a type name and do what you gotta do.
 
    
    - 3,485
- 1
- 15
- 18
I believe that you are looking for reflection.
Check out this question: What is reflection and why is it useful?
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 "); }
}
 
    
    - 1,362
- 16
- 25
 
     
     
     
    