简体   繁体   中英

Java constant objects and fields

I want to make a file, which is called ObjectsInfos.java It has too many objects' info. Which way is the best to implement the problem? Which one is the most effective? Singleton ? Inheritance? ..?

Thanks for helping.

.. Edit. The informations will be added later. So I must write the informations to a new java file.

//ObjectsInfos.java
    public class ObjectsInfos{

         public class Object1Info{
              static final int attr1 = 1;
              static final int attr2 = 5;
         }

         public class Object2Info{
              static final int attr1 = 3;
              static final int attr2 = 6;
         }
    }
    ---------------------------
    //Another java class
        static void main(){
            myGenericMethod(ObjectsInfos.Object1Info.attr1, ObjectsInfos.Object1Info.attr2);
            myGenericMethod(ObjectsInfos.Object2Info.attr1, ObjectsInfos.Object2Info.attr2);
        }

Sounds to me like you are looking for an enum .

public enum ObjectsInfos{
    Object1Info(1,5),
    Object2Info(3,6);
    private final int attr1;
    private final int attr2;

    ObjectsInfos(int attr1, int attr2) {
        this.attr1 = attr1;
        this.attr2 = attr2;
    }

    public int getAttr1() {
        return attr1;
    }

    public int getAttr2() {
        return attr2;
    }
}

You could also define a set of enumerations inside of a class. For example if you think about food and its categories:

public class Food {

    private Food() {
    }

    enum Fruit {
        BANANA,
        ORANGE
    }

    enum Vegetable {
        CARROT,
        LETTUCE
    }

    enum Cereal {
        CORN,
        WHEAT
    }

    enum Meat {
        COW,
        PORK
    }

    enum Sauce {
        TOMATOE,
        MUSTARD
    }
}

Enums are a robust alternative to the simple String or int constants. They offer you some methods out of the box like values or valueOf which can be very convenient and type safety on top of it (which you will not get with just ints ).

Here is a simple example on how you can use the above enumeration:

import java.util.Arrays;
import java.util.stream.Stream;

public class FoodMain {

    public static void main(String[] args) {
        System.out.println(isCereal("bla"));
        System.out.println(isCereal("wheat"));
        Stream.of(Food.Fruit.values()).forEach(System.out::println);
    }

    private static boolean isCereal(String cereal) {
        return Arrays.stream(Food.Cereal.values()).anyMatch(c -> c.toString().equalsIgnoreCase(cereal));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM