How to store Java types and allow only some specific types?

Suppose I want to have a class descriptor for records, where each record has a set of properties

Each attribute has a unique name and should have a specific type corresponding to a specific Java type, such as integer, string, short, double

The list of possible types should be limited. For example, I only support integer and string

private HashMap<String,Class> attributeList = new HashMap<String,Class>();

In the above example, HashMap is the attribute list, where key is the attribute name, and the value should be the attribute type (integer or string)

What is the best way to limit the definition of HashMap values?

Solution

Of course, you can add a map to the element using the wrapping method and check integer and sring However, you will only encounter runtime errors I agree with your restriction type to get static errors much better

For this, I won't actually use integer Class and string Class, but enumeration:

enum Types { String,Integer };

private Map<String,Types> attributeList = new HashMap<String,Types>();

to update:

To think of it, there is another (but more complex) solution. If you have to adhere to class objects: you can use the false enumeration mode, that is, use a set of constants (usually integer 2 ^ I am used) like an enumeration, so you can define your class objects as constants That certainly doesn't guarantee that no other class objects will be put into the map This is why Joshua Bloch's item 30 says "use enumerations instead of int constants" However, you can use the checker framework to provide additional type systems for your constants by using a pseudo enumeration checker:

@SuppressWarnings("fenum:assignment.type.incompatible")
public class TypeEnum {
  public static final @Fenum("Types") Class INT_CONST = Integer.class;
  public static final @Fenum("Types") Class STR_CONST = String.class;
}

You can then define the map using type category restrictions:

private HashMap<String,@Fenum("Types") Class> attributeList
   = new HashMap<String,@Fenum("Types") Class>();

Of course, you need to include fenum checker in the compiler

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>