[英]Passing class name as parameter
I have 3 classes called RedAlert
, YellowAlert
, and BlueAlert
. 我有3个名为RedAlert
, YellowAlert
和BlueAlert
。
Within my class AlertController
I want to have a method like this: 在我的类AlertController
我希望有一个像这样的方法:
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? 如何将类名作为参数,并根据该类名从类名创建适当的对象?
Using reflection it is possible. 使用反射是可能的。 Here for a given className (passed as a string) . 这里是给定的className(作为字符串传递)。 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();
}
}
Instead of passing the class name, you can pass the class itself and use reflection to create a new instance of the class. 您可以传递类本身并使用反射来创建类的新实例,而不是传递类名。 Here's a basic example (assuming all your XxxAlert
classes extend from an Alert
class): 这是一个基本示例(假设您的所有XxxAlert
类都从Alert
类扩展):
public <T extends Alert> void setAlert(Class<T> clazzAlert) {
Alert alert = clazzAlert.newInstance();
//use the alert object as you want/need...
}
Now you just call the method like this: 现在你只需调用这样的方法:
setAlert(RedAlert.class);
Note that it would be better using a super class in T
parameter, otherwise you (or another programmer) could do this: 请注意,在T
参数中使用超类会更好,否则您(或其他程序员)可以这样做:
setAlert(Object.class);
which would be plain wrong. 这是完全错误的。
While you can create it using Reflection etc... I'd suggest investigating some Creational Design Patterns. 虽然您可以使用Reflection等创建它...我建议调查一些创建设计模式。
Specifically the Factory Pattern 特别是工厂模式
Here is a (very) crude example: 这是一个(非常)粗略的例子:
public interface Alert {
}
public class BlueAlert implements Alert {
}
public class RedAlert implements Alert {
}
public class YellowAlert implements Alert {
}
public final class AlertFactory {
public <T extends Alert> Alert create(Class<T> clazz) {
Alert toReturn = null;
if (RedAlert.class.equals(clazz)) {
toReturn = new RedAlert();
} else if (YellowAlert.class.equals(clazz)) {
toReturn = new YellowAlert();
} else if (BlueAlert.class.equals(clazz)) {
toReturn = new BlueAlert();
}
return toReturn;
}
}
And then from your Method you could use: 然后从你的方法中你可以使用:
public void SetAlert(Class alertClass) {
Alert theAlert = new AlertFactory().create(alertClass);
}
Anyway, while this is a really ugly example, I'm trying to highlight that maybe you could look at the Creational Patterns and solve your problem a different way without passing classnames around. 无论如何,虽然这是一个非常丑陋的例子,但我想强调一下,也许你可以看看Creational Patterns并以不同的方式解决你的问题而不传递类名。
Why not use a factory pattern approach. 为什么不使用工厂模式方法。
public interface Alert {}
public class RedAlert implements Alert {}
public class YellowAlert implements Alert {}
public class BlueAlert implements Alert {}
public interface AlertFactory {
Alert create();
}
public class RedAlertFactory implements AlertFactory {
public Alert create() {
return new RedAlert();
}
}
public class YellowAlertFactory implements AlertFactory {
public Alert create() {
return new YellowAlert();
}
}
public class BlueAlertFactory implements AlertFactory {
public Alert create() {
return new BlueAlert();
}
}
// your setAlert method could probably look like this
public void setAlert(AlertFactory factory) {
aInstance = factory->create();
}
Then you could do something like this. 然后你可以做这样的事情。
setAlert(new RedAlertFactory()); // or YellowAlertFactory, BlueAlertFactory
It's possible to use your approach using java.lang.Class#newInstance . 可以使用java.lang.Class #newInstance来使用您的方法。
You can have a reference of Class in your method signature, something like this: 您可以在方法签名中引用Class,如下所示:
public void SetAlert(Class class)
Then in your method you can create the instance of the input class using the newInstance method: 然后在您的方法中,您可以使用newInstance方法创建输入类的实例:
Object obj = class.newInstance();
What about this - 那这个呢 -
public void SetAlert(Class<?> class){
Object obj = class.newInstance();
if(obj isInstanceOf RedAlert){
RedAlert ra= (RedAlert)obj;
}
...
}
避免内部依赖和初始化:
AlertController aController = new AlertController(new RedAlert());
Use enums: 使用枚举:
public enum AlertType {RED_ALERT, YELLOW_ALERT, BLUE_ALERT};
// ...
public void SetAlert(AlertType type)
{
// ...
}
// ...
AlertController aController = new AlertController();
SetAlert(AlertType.RED_ALERT);
Many options: 很多选择:
Use Java Reflection to create object from Class object. 使用Java Reflection从Class对象创建对象。 Declare your method like this: 像这样声明你的方法:
public void SetAlert(Class clazz)
{
Constructor<?> ctor = clazz.getConstructor();
Object object = ctor.newInstance();
}
And then, 然后,
AlertController aController = new AlertController();
SetAlert(RedAlert.class);
This is the way to create an instance using a class name. 这是使用类名创建实例的方法。 The concrete type of Alert
must have a public constructor that takes no arguments. Alert
的具体类型必须具有不带参数的公共构造函数。
private Alert alert;
public void setAlert(String className)
{
try {
Class<?> raw = Class.forName(className);
Class<? extends Alert> type = raw.asSubclass(Alert.class);
Constructor<? extends Alert> ctor = type.getConstructor();
this.alert = ctor.newInstance();
} catch (Exception ex) {
throw new IllegalArgumentException("Invalid Alert implementation.", ex);
}
}
The caller would use it like this: 调用者会像这样使用它:
AlertController aController = new AlertController();
controller.setAlert("com.y.foo.RedAlert");
If you create a convention for passing a certain set of parameters to the constructor, you can do that too, but you'll need to do a little extra work in the getConstructor()
call to find it. 如果你创建了一个约定,用于将一组特定的参数传递给构造函数,你也可以这样做,但是你需要在getConstructor()
调用中做一些额外的工作来找到它。 You can also use constructors that aren't public, but, again, that takes a bit of extra work. 您还可以使用非公共构造函数,但同样需要一些额外的工作。
The suggestions to pass the class literal, RedAlert.class
, don't make much sense. 传递类文字RedAlert.class
的建议没有多大意义。 If the RedAlert
class is available to the caller at compile time, you'd just use its constructor, new RedAlert()
. 如果RedAlert
类在编译时可供调用者使用,那么您只需使用其构造函数new RedAlert()
。
Another way you can do this without using reflection is to have an Interface say Alert and have your classes - RedAlert, YellowAlert, and BlueAlert implement the Alert interface. 另一种不使用反射就可以做到这一点的方法是让一个接口说出Alert并让你的类--RedAlert,YellowAlert和BlueAlert实现Alert接口。
So now your method in AlertController looks like: 所以现在你在AlertController中的方法看起来像:
public void setAlert(Alert alert) {
// Your code goes here
}
Now you can do : 现在你可以这样做:
setAlert(new RedAlert());
setAlert(new YellowAlert());
setAlert(new BlueAlert());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.