Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing class name as parameter

Tags:

java

I have 3 classes called RedAlert, YellowAlert, and BlueAlert.

Within my class AlertController I want to have a method like this:

public void SetAlert(//TAKE IN NAME OF CLASS HERE//)
{
    CLASSNAME anInstance = new CLASSNAME();
}

So for example I want to:

AlertController aController = new AlertController();
SetAlert(RedAlert);

How do you take in the class name as a parameter, and based on that class name create the appropriate object from the class name?

like image 305
1110101001 Avatar asked Jul 25 '13 05:07

1110101001


People also ask

Can we pass class name as parameter in Java?

Note that the parameter className must be fully qualified name of the desired class for which Class object is to be created. The methods in any class in java which returns the same class object are also known as factory methods. The class name for which Class object is to be created is determined at run-time.

Can a class be a parameter?

A class parameter defines a special constant value available to all objects of a given class. When you create a class definition (or at any point before compilation), you can set the values for its class parameters.

Can we use class name as variable?

Answer : Yes we can have it.

How do you pass a class name as an argument in Python?

yes of coarse you can pass classes or functions or even modules ... def foo(): pass here it gives it address for ex. function foo at0x024E4463 means it is given address of foo function but in class itdoesnt means class foo: pass here it gives <class.


1 Answers

Using reflection it is possible. Here for a given className (passed as a string) . This class will be searched in memory ( it should be already loaded).

The name of the class to be instantiated when passed as a string should be fully qualified

void createInstanceOfClass(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException{


        Class classTemp = Class.forName(className);

        Object obj =classTemp.newInstance();



    }
}
like image 157
Sanyam Goel Avatar answered Sep 17 '22 21:09

Sanyam Goel