Maverik
Maverik

Reputation: 2408

Use reflection to create classes at runtime

I have to create a list of objects, which are configured according to the name of some classes received as input.

For each object I have to call a method, which add an operation that is created dynamically.

However I don't know exactly ho to resolve the problem. Please see an example below.

String className; // this is an input parameter

final Class<?> classType = Class.forName(className);

// here I would like to use classType instead of "?" but it gives me an error.
Task<?> task = TaskFactory.createTask((String)classType.getField("_TYPE").get(null))); 

tasks.put(task, null);

task.addOperation(new Operation<classType>() { // this gives an error 

   @Override
   public void onNewInput(classType input) { // this gives an error 

        System.out.println(input)
   }
});

Upvotes: 1

Views: 223

Answers (1)

Marco13
Marco13

Reputation: 54689

As you can see from the comments, the surrounding infrastructure and the intention are not entirely clear. However, you can achieve a certain degree of type-safety with a "helper" method that captures the type of the given Task, and allows you to work with this type internally:

public class RuntimeType
{
    public static void main(String[] args) throws Exception
    {
        String className = "";
        final Class<?> classType = Class.forName(className);
        Task<?> task = TaskFactory.createTask((String)classType.getField("_TYPE").get(null));
        addOperation(task);
    }

    private static <T> void addOperation(Task<T> task)
    {
        task.addOperation(new Operation<T>() 
        { 
            @Override
            public void onNewInput(T input) 
            { 
                System.out.println(input);
            }
        });        
    }
}

class TaskFactory
{
    public static Task<?> createTask(String string)
    {
        return null;
    }
}

class Task<T>
{
    public void addOperation(Operation<T> operation)
    {
    }

}

interface Operation<T>
{
    void onNewInput(T input);
}

Upvotes: 1

Related Questions