1

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.

Rupesh Yadav
  • 12,096
  • 4
  • 53
  • 70
Lolmister
  • 243
  • 1
  • 3
  • 7

6 Answers6

8

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.

sp00m
  • 47,968
  • 31
  • 142
  • 252
1

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.

Sergii Zagriichuk
  • 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
0

You can use reflection to switch on a type name and do what you gotta do.

bluevector
  • 3,485
  • 1
  • 15
  • 18
0

I believe that you are looking for reflection.

Check out this question: What is reflection and why is it useful?

Community
  • 1
  • 1
wsidell
  • 712
  • 7
  • 14
0

I think that Class.forName might be what you're looking for

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

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 "); }

}

loknath
  • 1,362
  • 16
  • 25