I was writing a quick method that is using Google Gson to translate an Object to JSON. It’s simple, but I wanted to centralize my JSON building process in case I want to make further changes:
public static String buildJSONObject(Object obj) {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
return gson.toJson(obj);
}
And now I have two questions regarding this (which works),
-Is using Object okay as a method argument, or is there a better way using Generics?
-Is there performance overhead if constantly casting Objects to whatever kind of object is passed to the method?
Generics offer type safety and show intent better, leading to cleaner code. That being said, they really only offer these benefits when you know what kinds of objects you want to pass to the method and you have established some kind of object heirarchy which you extend all your JSON’able objects from. If you really want to be able to turn any object under the sun into JSON,
Object objis the way to go.There are no performance problems with casting. What you should be worried about is type safety and RuntimeExceptions from invalid casts. Be careful of doing casts if you are certain of the types of objects going into your method. You can always do a safe cast with a
instanceofcheck first as well which will make this less of a problem.