How to instantiate class from String?

Hi,

I looked at :

And tried this in plain Java and can’t figure how to get it work :

// Test.java

public class Test {

  class TestA {
    TestA() {}
  }

  class TestB {
    TestB() {}
  }

  class TestC {
    TestC() {}
  }

  public static void main(String[] args) {
    try {
      Object test = Class.forName("Test$TestA").newInstance();
    } catch(Exception e) {
      System.out.println(e);
    }
  }
}
$ javac Test.java && java Test
java.lang.InstantiationException: Test$TestA

But as mentioned by others, the factory pattern seems more adapted to your situation.

If you have to deal with a large amount of different cars that you want to read from files, you should use JSON or Java’s serializing system to read and write objects to files as described here :