Wesley Gijzen
Wesley Gijzen

Reputation: 67

Java: initialising a class from a string

Say I have a class called ModelX, but my program doesn't know about this class untill runtime.

So to create it I can't do:

private ModelX aModel;

Because it doesn't know its name or its existance yet, the only thing it does do is read its name from say a simple .txt file.

How can I make it load the class from a string and then get its constructor, so that I can do

String x = "ModelX";
cls = Class.forName("x");
Object obj = cls.newInstance();

for example, so that I can do

aModel = new obj();

and

private obj aModel;

I'm sorry if the description is vague but I do not really know how to describe what I want.

I need to be able to do this:

aModel = new ModelX();
private ModelX aModel;

While I got ModelX from a string.

Upvotes: 1

Views: 116

Answers (3)

Vishwa
Vishwa

Reputation: 26

Reflection can be used as follows,

String x = "com.example.ModelX";
Class cls = Class.forName(x);
Object obj = cls.newInstance();

Upvotes: 0

nneonneo
nneonneo

Reputation: 179392

Java isn't going to allow you to refer to a type that isn't known at compile-time. Therefore, it is not possible to write

private ModelX aModel;

if ModelX will only be known at runtime.

You have a few ways around this:

  • You can define your own ModelX, in the same package etc., which has all the same methods and interfaces, but which has purely stub implementations. You can arrange for the real implementation will be pulled in at runtime (e.g. by compiling your stub into a .class file that won't be included in the final .jar). This is what Android does, for example, to provide Eclipse with browsable Android classes that are only actually implemented on the device.
  • You can define a proxy class, named similarly (or e.g. ModelProxy), which implements all the same methods, forwarding them to the runtime-loaded class via reflection.

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279920

First, the Class.forName() method expects the fully qualified class name. The is the class simple name, for example ModelX, appended to its package name separated by a . For example

package com.example;

public class ModelX {...}

you would use it as

Class clazz = Class.forName("com.example.ModelX");

Second, the class Class has a a few method to get Constructor instances. You can see and read about those in the javadoc. If your ModelX class has an accessible no-args constructor, you can directly call it with

Object instance = clazz.newInstance();

You'll need to cast it appropriately.

Upvotes: 3

Related Questions