lundi 25 avril 2016

Iteration using reflection through Object constants in an interface

I was trying to implement something like enum by myself. While i was trying to iterate my constant objects i came across using reflection and i stumbled upon java.lang.reflect.Field . So here is my scenario. I have an entity class for holding a pair of String constants

public class ConstantEntity {

        private String constantName;
        private String constantDesc;

        ConstantEntity(String name, String desc) {
                this.constantName = name;
                this.constantDesc = desc;
        }

        public String constantName() {
                return this.constantName;
        }

        public String constantDesc() {
                return this.constantDesc;
        }

}

And I have a interface where i create the constants using the entity

public interface MyConstantsPool { 

public static final ConstantEntity CONSTANT_ONE = new ConstantEntity("bla1", "11");
public static final ConstantEntity CONSTANT_TWO = new ConstantEntity("bla2", "12");
public static final ConstantEntity CONSTANT_THREE  = new ConstantEntity("bla3", "13");


}

And i am trying to consume and iterate through these constants using

import java.lang.reflect.Field;

public class ConsumeConstants {

        public static void main(String args[]) {

                Field[] fields = MyConstantsPool.class.getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {

                        Object myConstant = fields[i];
                        ConstantEntity typeSafeEnum = (ConstantEntity) myConstant ;
                        System.out.println(" The name: "
                                        + ((ConstantEntity) typeSafeEnum).constantName());
                        System.out.println(" The description: "
                                        + ((ConstantEntity) typeSafeEnum).constantDesc());

                }
        }
}

I went through the documentation, but i couldn't grasp the idea behind Field. Am I completely wrong in the understanding of using reflection? When do we use Field? And what is the proper way to iterate through all the Object constants in the interface?

NOTE: I am using java 1.4; So i have to use basic java features to implement this.





Aucun commentaire:

Enregistrer un commentaire