# 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:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![molo32](https://avatars.discourse-cdn.com/v4/letter/m/a87d85/32.png) [@molo32](https://discourse.processing.org/u/molo32)\
**Post date:** [February 7, 2021, 1:00am UTC](https://discourse.processing.org/t/how-to-instantiate-class-from-string/27641/1 "2021-02-07T01:00:16Z")

</div>

instantiate class from string

I have the car class

```auto
class car {
...
}

```

how can I do

```auto
ArrayList <Object> cars = new ArrayList <Object> (); // Create an ArrayList object

String s = "car"

cars.add (new s())

```

I tried this but it gives me an error

```auto
 
    try {     
   cars.add( Class.forName( getClass().getName() +"$car").newInstance() );
    
 } catch ( Exception e) {print(e);}

```

```auto
java.lang.InstantiationException: car_game$car

```

what I mean is instantiate a class from a string  
something like new “car” (), not new car ()  
I have a .txt file with the name of several classes.

```
txt file cars.txt
------
car_mo
car_sd
car_dave
----

```

and when loading the .txt I want to instantiate the classes that the .txt has written.

ej

```
String[] txt=loadString("cars.txt")
cars.add (new txt[0]()) //instead of cars.add (new car_mo())
cars.add (new txt[1]()) //instead of cars.add (new car_sd())

```

i am using ide processing , windows7

---

<div class="post-metadata">

**Author:** ![paulgoux](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@paulgoux](https://discourse.processing.org/u/paulgoux)\
**Post date:** [February 7, 2021, 1:13am UTC](https://discourse.processing.org/t/how-to-instantiate-class-from-string/27641/2 "2021-02-07T01:13:24Z")

</div>

Do

```auto
cars.add (new car(s) ) ;

```

And you need your constructor to look like this

```auto
class car {
   String name;
   car(String s) {
      name = s;
   } 
}

```

Also your arraylist should now be

```auto
ArrayList <car> cars = new ArrayList <car> ();

```

---

<div class="post-metadata">

**Author:** ![molo32](https://avatars.discourse-cdn.com/v4/letter/m/a87d85/32.png) [@molo32](https://discourse.processing.org/u/molo32)\
**Post date:** [February 7, 2021, 1:19am UTC](https://discourse.processing.org/t/how-to-instantiate-class-from-string/27641/3 "2021-02-07T01:19:13Z")

</div>

what I mean is instantiate a class from a string  
something like new “car” (), not new car ()  
I have a .txt file with the name of several classes and when loading the .txt I create the classes that have the txt written.

---

<div class="post-metadata">

**Author:** ![paulgoux](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@paulgoux](https://discourse.processing.org/u/paulgoux)\
**Post date:** [February 7, 2021, 9:29am UTC](https://discourse.processing.org/t/how-to-instantiate-class-from-string/27641/4 "2021-02-07T09:29:56Z")

</div>

> <https://stackoverflow.com/questions/2215843/using-reflection-in-java-to-create-a-new-instance-with-the-reference-variable-ty>

---

<div class="post-metadata">

**Author:** ![cansik](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/cansik/32/8815_2.png) [@cansik](https://discourse.processing.org/u/cansik)\
**Post date:** [February 7, 2021, 9:39am UTC](https://discourse.processing.org/t/how-to-instantiate-class-from-string/27641/5 "2021-02-07T09:39:28Z")

</div>

I would not suggest to use reflection for that. You have a limited number of classes you want to instantiate, so what you usually do in software engineering is using a [factory pattern](https://www.tutorialspoint.com/design_pattern/factory_pattern.htm).

Just create a factory that takes in a string and creates your class. The advantage over reflection is speed and also it is less error prone.

Or try to think about, if the car characteristic “mo, sd, dave” could not be an attribute of the class? Why does it have to be it’s own class (does it even have it’s own behaviour)? The need to use reflection usually is an indicator of a problem in your object oriented architecture and not the solution to it.

---

<div class="post-metadata">

**Author:** ![quark](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/quark/32/26_2.png) [@quark](https://discourse.processing.org/u/quark)\
**Post date:** [February 7, 2021, 9:45am UTC](https://discourse.processing.org/t/how-to-instantiate-class-from-string/27641/6 "2021-02-07T09:45:21Z")

</div>

> [@molo32](#):
>
> ```auto
> car_mo
> car_sd
> car_dave
> 
> ```

What is the difference between these classes?

---

<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?

---

<div class="post-metadata">

**Author:** ![foxfabi](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/foxfabi/32/12272_2.png) [@foxfabi](https://discourse.processing.org/u/foxfabi)\
**Post date:** [March 2, 2021, 8:25pm UTC](https://discourse.processing.org/t/how-to-instantiate-class-from-string/27641/8 "2021-03-02T20:25:02Z")

</div>

Hello,  
Hope the following information will help …

I’m using a factory pattern to create different polygon instances.  
The polygons inherit an abstract class.

```auto
// Define this global variables
Class self;
 // if your sketch is called sample.pde, use sample as type for that
sample that;

// Add this to your sketch setup()
self = getClass();
that = this;

// The abstract class from which all polygons will inherit
abstract class Shape {
    float x = 0; float y = 0;
    Shape(String type, float _x, float _y) {
      this.x = _x;
      this.y = _y;
    }
}

// The classes for the different polygons
class ShapeA extends Shape {
  ShapeA(float x, float y) {
    super("ShapeA", x, y);
  }
}
class ShapeB extends Shape {
  ShapeB(float x, float y) {
    super("ShapeB", x, y);
  }
}
...
// Probably the most important. 
// Create instances based on the class name
class Factory {
  Shape newShape(String type, float x, float y) {
    Shape shape = null;
    try {
      Class<?> shapeClass = Class.forName(self.getName() + "$" + type);
      Constructor<?>[] constructors = shapeClass.getDeclaredConstructors();
      Constructor instance = constructors[0]; // use first constructor
      instance.setAccessible(true);
      shape = (Shape) instance.newInstance(that, x, y);  
    }
    catch (ClassNotFoundException e) {
      e.printStackTrace();
    } 
    catch (Exception e) {
      e.printStackTrace();
    }
}

// Create an instance using the class name
shape = factory.newShape("ShapeA", x, y);

```
