# How to instantiate class from String?

**URL:** <https://discourse.processing.org/t/how-to-instantiate-class-from-string/27641>\
**Category:** Coding Questions\
**Created:** [February 7, 2021, 1:00am UTC](https://discourse.processing.org/t/how-to-instantiate-class-from-string/27641 "2021-02-07T01:00:16Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![josephh](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/josephh/32/210_2.png) [@josephh](https://discourse.processing.org/u/josephh)\
**Post date:** [February 7, 2021, 5:11pm UTC](https://discourse.processing.org/t/how-to-instantiate-class-from-string/27641/7 "2021-02-07T17:11:29Z")

</div>

Hi,

I looked at :

> <https://stackoverflow.com/questions/9886266/is-there-a-way-to-instantiate-a-class-by-name-in-java>

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

```auto
// 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);
    }
  }
}

```

```shell
$ 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 :

> [@System for saving objects](https://discourse.processing.org/t/system-for-saving-objects/25935):
>
> I want to create a system for saving objects. I have three classes, that I want to save, to json format, but I don’t want to write by hand every variables. Is there any way that I can move the entire object to json format right away?

---

_[View the full topic](https://discourse.processing.org/t/how-to-instantiate-class-from-string/27641)._
