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.

  • possible duplicate of [Getting class by its name](http://stackoverflow.com/questions/10119956/getting-class-by-its-name) – Domi Dec 01 '13 at 13:56
  • Take a look at [this answer](http://stackoverflow.com/a/2408812/1114687). – n.st Dec 01 '13 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.) – Hot Licks Dec 01 '13 at 14:05

2 Answers2

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

Domi
  • 22,151
  • 15
  • 92
  • 122
  • 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 Dec 01 '13 at 14:41
  • @user3054461 Use [Class.cast](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#cast(java.lang.Object)) – Domi Dec 01 '13 at 15:16
1

Try using the class of your object:

if (boat1.getClass().getSimpleName().equals(type)) {
    System.out.println("boat1 is a motorboat");
}
eugene82
  • 8,432
  • 2
  • 22
  • 30