samedi 4 mars 2017

Java - Substitue reflection to improve performance

I'm using this to put classes into a hashmap, but this method uses reflection, therefore performance is slower.

How do I do this without using reflection? I was told to utilise Supplier but I have casting problems using Supplier, an example would be more helpful as I am still quite new to using java.

enum: anClass will be set as the object to the key LoadTask in the map:

class Player{
    HashMap<LoadTask, Object> anMap;
}

Where object is = anClass.

enum LoadTask{
    CLASS_A(ClassA.class),
    CLASS_B(ClassB.class);
    Class<?> anClass;
    LoadTask(Class<?> anClass){
        this.anClass = anClass;
    }
}

NOTE: ALL CLASSES STORED WILL IMPLEMENT INTERFACE AwsomeClass, ALLOWING EASY ACCESS TO THE ABSTRACT METHOD: void doThing();

This is the bit I'm needing help improving:

public static void init(Player p){
    for (LoadTask a : LoadTask.values()){
        if (a.anClass == null) //Because I use the enum for different items too
            continue;
        Object task = p.anMap.get(a);
        if (task == null){ //if task = null, as will be when a new Person is created, it will set a new instance class for him/her.
                try {
                    p.anMap.put(a, a.anClass.newInstance());
                } catch (InstantiationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

        }
    }
}

For context... This is what this will ultimately be used for:

public static void doThingTasks(Player p){
    for (LoadTask a : LoadTask.values()){
        if (a.anClass == null)
            continue;
        AwsomeClass b = (AwsomeClass) p.anMap.get(a);
        b.doThing();

    }
}

Before changing to

Class<?> anClass;

I was using:

Object anClass;

and then doing:

CLASS_A(new ClassA()),

but then ofcourse only one instance would exist: the instance created when the enum was created, and I want a new instance created for each person.





Aucun commentaire:

Enregistrer un commentaire