Creating an object from a variable

Hello all,

I’m just wondering if it’s possible to create an object from a variable String. For example, I have four classes named Tile1, Tile2, …, etc. Now say I have a String, from which an ID character (1 - 4) is incremented into the String, could I create a class-object from that String? Like so:

char id = '2'; // This character is arbitrary in my actual program, but just initiated as '2' for this example.
String name = "Tile"+id;
Tile t = new name(); // All Tile1...4 classes extend the main class, Tile.

Of course, the code above doesn’t work because the compiler thinks I’m trying to create an object of class name, which doesn’t exist. But is there any possible way to create an object of a class from a String, like above?

Class.forName(name).newInstance();

Kev

Thanks a lot, kevglass! However, I’m getting InstantiationException:

java.lang.InstantiationException: Tile1
        at java.lang.Class.newInstance0(Class.java:281)
        at java.lang.Class.newInstance(Class.java:249)
        at Tiles.<init>(Tiles.java:34)
        at Tiles.main(Tiles.java:88)

I’m assuming this happens since both my main Tile class and all of my Tile1…4 classes require parameters. Is there anyway to pass parameters to the newly created Object too?

EDIT: Yup, I get an error because my classes require parameters (I tested it by removing the parameter requirements of my classes). I guess I can just use a separate method, and after the Object is initiated, call that method.

Yeah, it just gets a bit more complicated, you really want to have a lot at the Java Reflection API.

In this case you’d do something like:


Class.forName(name).getContructors()[0].newInstance(args);

Kev

Hmm, according to the constructor of this:

Class.forName(name).getContructors()[0].newInstance(args);

An Object is required. What am I supposed to pass to that?

The values for your arguments

Kev

Hey thanks ! I did not know that either.So let’s say the Class’s constructor needs 2 BufferedImages we will do it like that?
Class.forName(name).getContructors()[0].newInstance(image1 , image2); ?

Where ofcourse image1 and image2 are 2 BufferedImages?

new Object[]{image1, image2}

Ahh thanks for the clarafication Riven. So say I had a Class that required two Strings, this would suffice:

Object ob = new Object() {
	String a = "String A";
	String b = "String B";
};

Class.forName("Test").getContructors()[0].newInstance(ob);

Assuming the arguments are named a and b.

I’d suggest you’d not only ask, but also try to compile it and see what error-messages are reported, because the above code will never compile.

Object[] arr = new Object[]{ “String A”, “String B” };

or

Object[] arr = new Object[2];
arr[0] = “String A”;
arr[1] = “String B”;

Ahh okay I see now. Sorry about that.