anish
anish

Reputation: 7422

Reducing if else to determine the dataType

How to reduce this usiong reflection

private static Object determineDataType(final String value, String dataType)
{
    System.out.println("Name--->>" + dataType);
    if(dataType.equals(Boolean.class.getName()))
    {
       return new Boolean(value);
    }
    else if(dataType.equals(String.class.getName()))
    {
        return new String(value);
    }
    else if(dataType.equals(Character.class.getName()))
    {
        return new String(value);
    }
    else if(dataType.equals(Byte.class.getName()))
    {
        return new Byte(value);
    }
    else if(dataType.equals(Short.class.getName()))
    {
        return new Short(value);
    }
    else if(dataType.equals(Integer.class.getName()))
    {
        return new Integer(value);
    }
    else if(dataType.equals(Long.class.getName()))
    {
        return new Long(value);
    }
    else if(dataType.equals(Float.class.getName()))
    {
        return  new Float(value);
    }
    else if(dataType.equals(Double.class.getName()))
    {
        return  new Double(value);
    }
    //defualt return the String value, Lets' AOPI do the Validation
    return new String(value);
}

Upvotes: 0

Views: 214

Answers (3)

John Watts
John Watts

Reputation: 8885

I don't think you could reduce the amount of code with reflection here. First, the reflection APIs are pretty verbose. Second, you are doing slightly different things in some of the blocks. In particular, the block for Boolean does more than just call a constructor.

Upvotes: 0

alain.janinm
alain.janinm

Reputation: 20065

You can use Class.forName and method getConstructor (here is an example):

Object instance = Class.forName(dataType)
         .getConstructor(new Class[] {String.class})
         .newInstance(new Object[]{value});

By the way it will not work for Character and Boolean because you make a special treatment for them.

Upvotes: 1

Torious
Torious

Reputation: 3424

I, too, wonder why in the world you would do this. But, setting that aside for a minute, here's some untested code:

List<Class<?>> types = Arrays.asList(Long.class, Integer.class, ... );
for (Class<?> type : types) {
    if (type.getName().equals(dataType))
        return type.getConstructor(String.class).newInstance(value);
    // TODO: catch exceptions and probably re-throw wrapped
}
return new String(value);

Upvotes: 1

Related Questions