0

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.

3
  • possible duplicate of Getting class by its name Commented Dec 1, 2013 at 13:56
  • Take a look at this answer. Commented Dec 1, 2013 at 13:56
  • Minor point: You are (I believe) wanting to convert a string to a class, not an object of the class. (A String already is an object.) Commented Dec 1, 2013 at 14:05

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

That works so far, but now I want to parse boat1 to the type that the user has given. What I want is: Motorboat boat2 = (type) boat1; That still doesn't work.
@user3054461 Use Class.cast
1

Try using the class of your object:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.