Androme
Androme

Reputation: 2449

Java string with name of class to class

Sorry about the strange topic name, could not find one that fitted well. To my problem, i want to create something dynamic in Java, it is a very simple class that can take an event and throw it along, sadly have the system i am using be made so each event must have it own method where the event is the argument of the method, but the good news is that we can add as many event listener classes as we want! I wan my program to be able to dynamic add and remove the methods that are being listened to, by add and remove the listen classes.

I am not good with Java but have a fair deal expirence with C#, so i attacked my problem as i would there and created this class.

public class TESPluginDynListener<T> implements Listener {

    TESPlugin plugin;

    public TESPluginDynListener(TESPlugin plugin){
        this.plugin = plugin;
    }

    @EventHandler(ignoreCancelled=false, priority = EventPriority.LOW)
    public void onDynEvent(T event){
        if(event instanceof Event)
            plugin.onEvent((Event)event);
    }
}

This seems to work fine, but my problem is, that the event i have to register do i get as a String, example "some.package.someEvent", and i have no idea how to translate that into the Type T so i can add the listener class.

So how can i create an instance my class TESPluginDynListener where T is translated from a String? I am not interested in doing a lot of if else, as i want this to be as dynamic as possible!

Here is an idea of what i am trying to do

String eventClass = "some.package.someEvent";

TESPluginDynListener listener = new TESPluginDynListener<Type.FromName(eventClass)>(this);
eventhandeler.RegisterListener(listener);

Upvotes: 1

Views: 173

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503964

It sounds like you're looking for Class.forName and Class.newInstance.

On the other hand, bear in mind that type erasure in generics means you don't really need to know T in order to build a TESPluginDynListener... you probably want to take Class<T> in the constructor for TESPluginDynListener and use Class.isInstance rather than instanceof within onDynEvent.

Upvotes: 7

Related Questions