简体   繁体   English

如何从类的字符串表示形式转换为该类的实例?

[英]How do I convert from the string representation of a class to an instance of the class?

I have a string representation of a class's path. 我有一个类路径的字符串表示形式。 It could be any of three classes, all of which implement the same interface, Adapter , but I don't know what the value is. 它可以是三个类中的任何一个,它们全部实现相同的接口Adapter ,但是我不知道值是什么。

  • "com.example.adapters.Music" “ com.example.adapters.Music”
  • "com.example.adapters.Video" “ com.example.adapters.Video”
  • "com.example.adapters.Photo" “ com.example.adapters.Photo”

Given only a variable holding one of the three strings above, how can I get a usable instance of the actual class? 给定一个仅包含以上三个字符串之一的变量,如何获得实际类的可用实例?

You can use: 您可以使用:

String name = "com.example.adapters.Music";
Object obj = Class.forName(name).newInstance();

You will then have to cast obj to the correct type (possibly by examining the name or by using instanceof ). 然后,您必须将obj转换为正确的类型(可能通过检查名称或使用instanceof )。 It is easier if your classes have a common base class (or interface that they implement) and you can use obj knowing only that it is some subclass. 如果您的类具有公共基类(或它们实现的接口),并且使用obj仅知道它是某个子类,则会更容易。

This will only work if the class has a default constructor. 仅当类具有默认构造函数时,此方法才有效。 Otherwise you will have to use reflection to get an instance of a constructor method and invoke it with the proper arguments. 否则,您将不得不使用反射来获取构造函数方法的实例,并使用适当的参数来调用它。

If a class has a no-argument constructor, then creating an object from its package-qualified class name (for example, "java.lang.Integer") is usually done using these methods: 如果一个类具有无参数构造函数,则通常使用以下方法从其包限定的类名称(例如,“ java.lang.Integer”)创建对象:

Class.forName
Class.newInstance


For e.g MusicClass mObj = Class.forName(<string name>).newInstance();

If arguments need to be passed to the constructor, then these alternatives may be used instead: 如果需要将参数传递给构造函数,则可以使用以下替代方法:

Class.getConstructor
Constructor.newInstance

您可以使用String数组保存三个字符串

String names[]= {"com.example.adapters.Music","com.example.adapters.Video","com.example.adapters.Photo"};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM