0

I have a use case, where I have stored the List of Java Data Types in DB, Like Byte, Character, Integer, Long, BigDecimal, BigInteger, Boolean.

So my use case is like If I read the value Long, I need to create the Long.class, if I read String, then String.class.

Class cls = Class.forName("java.lang.Long);, then I can use the cls for my own purpose.

I can achieve this, by having Enum of the above data types, as soon I read the value from the db, I pass the value to enum to get the class type. But I don't know whether it is efficient or not. Is there any method present in Java which gives like, for the given string,(without fully qualified name), it should return the class type.

1
  • Can you share some code? Commented May 20, 2020 at 14:54

1 Answer 1

1

Storing a reference to the Class object is efficient but using the Class object for reflection can be expensive. If you're just using the Class for reference then you're fine.

enum Decodable { BIG_INTEGER(BigInteger.class), INTEGER(Integer.class) // etc private final Class<?> decodableClass; private Decodable(Class<?> decodableClass) { this.decodableClass = decodableClass; } } 

You could also just maintain a Set of Class objects.

private static final Set<Class<?>> DECODABLE_CLASSES = ImmutableSet.of(Integer.class, BigInteger.class); //etc 
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, same way I thought of. Having Enum looks better. I do see few utilities in groovy provides like this but this returns ClassNode, not the class. import org.codehaus.groovy.ast.ClassHelper; ClassNode classNode = ClassHelper.make("String") I thought java might have some thing like this

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.