samedi 14 octobre 2017

Use Class methods using reflection

So I think my design got messed little, Here's what I got.

My application needs lots of enums, each contains multiple objects initialized and a "Get Best" method.

enum MyNumberEnum{
First("First", 1)
Third("Third", 3)

public String name;
public int num;

MyNumberEnum getBest(int num){
            MyNumberEnum bestNumber = First;
        for (MyNumberEnum number: MyNumberEnum.values()) {
            if (number.num <= num)
                bestNumber = number;
        }
        return bestNumber ;
}
}

All of the enums have the same getBest and all should have the field num, Because Enums cannot extend, Thought maybe interface might help here but if an enum implements an interface then each of it's instances just implement not the enum itslef.

public abstract class Best {

public abstract Enum<?> getBest(int num);
}

class MyNumberClass extends Best {
    public abstract Enum<?> getBest(int num){return MyNumberEnum.getBest(num)}
}

So I thought maybe Create a Class and inside put the Enum, Then I could extend the get best method.

So To make it easy to use, I created a HashMap And then added map.put("Number", MyNumberClass.class)

But then I got to a point which I got Class object, How can I use it's getBest method?

Thanks and sorry for my stupidness !





Aucun commentaire:

Enregistrer un commentaire