简体   繁体   English

如何将String解析为对象

[英]How to parse String to an object

First of all, I've already searched around a bit, but couldn't really find an answer for my problem. 首先,我已经进行了一些搜索,但是找不到真正的答案。 If such a thread alreay exists, I'm sorry. 如果存在这样的线程漏洞,对不起。 Also, I'm only at a beginner's level, so maybe i just didn't understand what was being explained and maybe I don't use the right terminology. 另外,我只是一个初学者,所以也许我只是不明白所解释的内容,也许我没有使用正确的术语。

I want to parse a String to an object type. 我想将String解析为对象类型。 For example: 例如:

Boat boat1 = new Motorboat();
String type = JOptionPane.showInputDialog(null, "Enter a type");
if(boat1 instanceof type)
{
    System.out.println("boat1 is a motorboat");
}

Boat is an abstract class and Motorboat is one of its subclasses. 船是抽象类,汽艇是其子类之一。

I know this won't work, because type is a String, but how can i make this work? 我知道这是行不通的,因为类型是字符串,但是我如何才能使它工作呢? How can i parse this String to an object type? 我怎样才能将此字符串解析为对象类型?

Thanks in advance. 提前致谢。

You can lookup a Class object from a string with Class.forName : 您可以使用Class.forName从字符串中查找Class对象:

String typeName = JOptionPane.showMessageDialog(null, "Enter a type");
Class<?> class = Class.forName(typeName);
if (class != null && class.isInstance(boat1))
{
    System.out.println("boat1 is a motorboat");
}

Pay special attention though because your comparison requires a fully qualified classname (that includes all packages). 但是,请特别注意,因为您的比较需要完全限定的类名 (包括所有包)。

Try using the class of your object: 尝试使用对象的类:

if (boat1.getClass().getSimpleName().equals(type)) {
    System.out.println("boat1 is a motorboat");
}

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

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