将类名作为参数传递
我有3类调用RedAlert
,YellowAlert
和BlueAlert
。
在我的课程中,AlertController
我想要一个这样的方法:
public void SetAlert(//TAKE IN NAME OF CLASS HERE//){
CLASSNAME anInstance = new CLASSNAME();
}
因此,例如,我想:
AlertController aController = new AlertController();SetAlert(RedAlert);
如何将类名作为参数,并基于该类名从类名创建适当的对象?
回答:
使用反射是可能的。这里是给定的className(作为字符串传递)。此类将在内存中搜索(应该已经加载)。
作为字符串传递时要实例化的类的名称应
void createInstanceOfClass(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException{ Class classTemp = Class.forName(className);
Object obj =classTemp.newInstance();
}
}
以上是 将类名作为参数传递 的全部内容, 来源链接: utcz.com/qa/407589.html