简体   繁体   中英

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. 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 :

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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