0

How can I give a class as a parametre in a method that I can then make one like that:

Type obj = new Type();

is that possible?

milkwood1
  • 385
  • 2
  • 3
  • 16

2 Answers2

0

Yes it is possible:

MyClass.class

Let's say you have this method:

private void doSomething(Class cls) {}

you'd call with

doSomething(MyClass.cls);

ACV
  • 9,964
  • 5
  • 76
  • 81
0

You can do it different ways.

  1. Pass a string parameter with full ClassName:

    void someMethod(String className) {    // className like "com.mypackage.Type"
        Type obj = (Type)Class.forName(className).newInstance();    
    }
    
  2. Pass a Class type:

    void someMethod(Class clazz) {    // clazz is Type.class
        clazz.newInstance();
    }
    
Ruslan
  • 6,090
  • 1
  • 21
  • 36