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?
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.
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.
Answer : Yes we can have it.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With