开发者

Is it okay to pass an Object object as method argument

开发者 https://www.devze.com 2023-03-20 23:04 出处:网络
I was writing a quick method that is using Google Gson to translate an Object to J开发者_Go百科SON. It\'s simple, but I wanted to centralize my JSON building process in case I want to make further cha

I was writing a quick method that is using Google Gson to translate an Object to J开发者_Go百科SON. 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?


Is using Object okay as a method argument, or is there a better way using Generics?

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 obj is the way to go.

Is there performance overhead if constantly casting Objects to whatever kind of object is passed to the method?

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 instanceof check first as well which will make this less of a problem.


Do you want to be able to pass any kind of object to the method? If so, the parameter type should be Object. That's all there is to it. Generics only offer value when they are actually doing something such as constraining an input type so that you can call certain methods on it, ensuring that multiple parameters to the method are related in some specific way or ensuring that the output type is related to the input type in some way, etc. In this case, a generic parameter would provide nothing that Object does not.

And you certainly shouldn't be worrying about any overhead from that (there likely isn't any, anyway). If you want to worry about overhead, worry about how you're creating a new instance of GsonBuilder to create a new instance of Gson every time the method is called, when you could just be reusing a single Gson object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号