user3054461
user3054461

Reputation: 25

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.

Upvotes: 0

Views: 146

Answers (2)

Domi
Domi

Reputation: 24508

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

Upvotes: 3

eugene82
eugene82

Reputation: 8822

Try using the class of your object:

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

Upvotes: 1

Related Questions