Reputation: 134
With an object of Class type, how to check if it's top level class / regular object class?
Context: I'm converting object metadata to json structure and currently my code looks like
JsonElement toJson(Type type) {
if (type == String.class) {
...
} else if (...) { //more primitives
...
} else if (type instanceof ParametrizedType) {
...
} else if (type instanceof Class) {
Class clazz = (Class) type;
if (clazz.isEnum()) {
....
}
// probably it's an object
}
}
Upvotes: 1
Views: 384
Reputation: 26926
You can invoke the method getSuperclass()
and check if the result is null or not:
Returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class. If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.
By the way don't reinvent the wheel... if you need to convert metadata to json use a json converter library. Using faster jackson for example you can do:
// Here object is any object and json string equivalent of this object
String json = new ObjectMapper().writeValueAsString(object);
Upvotes: 1