Fishy
Fishy

Reputation: 1303

Java Enum Value represent java.lang class

I am trying to create a program that creates it's own little database type thing(Just cause I want some extra stuff to do for it) and I have run into a small mishap. When I try and set the value for the value of the table, I obviously must check to see if it is the right type. In my Value class, I have the setValue function:

public void setValue(Object value){
    ValueType t = getColumn().getType();
    if(value instanceof t){
        // Is the correct type.
    }
    this.value = value;
}

Where ValueType is the Enum of the types of available values. Here is the class:

public enum ValueType {

    STRING, INTEGER, BOOLEAN, FLOAT

}

So that works until the line:

if(value instanceof t){

IntellIJ Idea is saying that t is an unknown class. So I am trying to make it so that t will represent a String or Integer. Thank you for your time, and help.

Upvotes: 0

Views: 204

Answers (1)

Tagir Valeev
Tagir Valeev

Reputation: 100309

You may add the following method to your enum:

public enum ValueType {
    STRING, INTEGER, BOOLEAN, FLOAT;

    public boolean isInstance(Object obj) {
        // Generate a class name from enum name
        String className = "java.lang."+name().substring(0, 1)+
                               name().substring(1).toLowerCase(Locale.ENGLISH);
        try {
            // Try to resolve this class and check the supplied object type
            return Class.forName(className).isInstance(obj);
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
}

Now you can write if(t.isInstance(value)).

However I would recommend to store the Class object in the enum, like this:

public enum ValueType {
    STRING(String.class), INTEGER(Integer.class), BOOLEAN(Boolean.class), FLOAT(Float.class);

    private Class<?> clazz;

    ValueType(Class<?> clazz) {
        this.clazz = clazz;
    }

    public boolean isInstance(Object obj) {
        return clazz.isInstance(obj);
    }
}

Upvotes: 2

Related Questions