samedi 4 mars 2017

Using enum and reflection to call methods over list of classes

I downloaded a project to learn java with, and I found an interesting way of modifying some big blocks of code, I'm still new to java so I don't know if what I did is more efficient/dangerous... Syntax 1 is the before, and Syntax 2 is my method.

Syntax 1:

class Person{

    TestClass testClass;
    TestClass2 testClass2;
    //etc...

    public Person(){
        testClass = new TestClass();
        testClass2 = new TestClass2();
        //etc...
    }

    void init(){
        testClass.init();
        testClass2.init();
        //etc...
    }



}

versus,

Syntax 2:

instead of doing:

person.testclass.doThing();

this method utilises a hashmap and stores classes as the object and uses an enum as the key.

TestClass tc = (TestClass) person.attribute.get(EnumKey.TEST_CLASS);
tc.doThing();

.

class Person{

    public HashMap<EnumKey, Object> attribute;

    public Person(){
        Class2.sendTasks(this); //sends all classes
    }

    void init(){
        class2.initTasks(this); //inits all
    }



}

.

class Class2{

    void sendTasks(Person p)
        for (EnumKey ek : EnumKey.values(){
            try {
                p.attribute.put(ek, ek.handshakeClass.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    void initTasks(Person p){
        for (EnumKey ek : EnumKey.values(){
            (TaskClass) tc = p.attribute.get(ek); //NOTE: all stored values (testclass1,2,3,etc) implement the interface TaskClass...
             tc.init();
        }
    }

}

.

enum EnumKey{

    TEST_CLASS(TestClass.class),

    TEST_CLASS2(TestClass2.class);


    Class<?> handshakeClass;
    EnumKey(Class<?> handshakeClass){
        this.handshakeClass = handshakeClass;

    }
}

Syntax 2 is soo much easier as I dont have to type out all the abstract methods of TaskClass each time I create a new class, I can just create a new enum field and the rest is done for me...

But is this a good method? Is it efficient? is it slower? risky?





Aucun commentaire:

Enregistrer un commentaire