在Java中用数字到数字转换的对象。(Object to number to number conversion in Java. Any methods in common libraries?)

编程入门 行业动态 更新时间:2024-10-24 20:15:34
在Java中用数字到数字转换的对象。(Object to number to number conversion in Java. Any methods in common libraries?)

我们的项目使用谷歌guava,Apache公用程序,也许其他库具有常见的任务,我想知道这些库是否包含空安全转换(对象到数字,对象到字符串)的方法。 至于现在我写了一些辅助方法,例如:

int parseInteger(Object obj) { if (obj!= null) { if (obj instanceof Integer) return (Integer) obj; if (obj instanceof Long) return ((Long) obj).intValue(); return Integer.parseInt(obj.toString()); } else { return 0; } }

Our project use google guava, apache commons and maybe other libraries with common tasks and I was wondering if these libraries contain methods which does null safe conversions (object to number, object to string). As for now I wrote myself some helper methods, e.g :

int parseInteger(Object obj) { if (obj!= null) { if (obj instanceof Integer) return (Integer) obj; if (obj instanceof Long) return ((Long) obj).intValue(); return Integer.parseInt(obj.toString()); } else { return 0; } }

最满意答案

我很确定在番石榴中没有这样的东西。 如前所述

番石榴试图强制你尽可能地避免使用null,因为在null存在的情况下,不正确的或无证的行为可能会导致大量的混淆和错误。 我认为尽可能避免使用空值绝对是一个好主意,如果您可以修改代码以使其不会使用空值,我强烈建议您采用这种方法。

类似的参数适用于parseEverythingAsInt 。 你正在寻找接受任何东西并返回一个int 。 这种方法的存在鼓励人们编写返回任何东西的方法。 这当然不是好的做法,因为严格有助于防止错误。 这就是为什么我很确定Guava没有这种方法。

也许我的回答最好是评论,但时间太长,我不认为会有积极的答案。

I'm pretty sure there's nothing like this in Guava. As already pointed

Guava tries to force you to avoid using null wherever possible, because improper or undocumented behavior in the presence of null can cause a huge amount of confusion and bugs. I think it's definitely a good idea to avoid using nulls wherever possible, and if you can modify your code so that it doesn't use null, I strongly recommend that approach instead.

A similar argument applies to parseEverythingAsInt. You're looking for a method accepting anything and returning an int. The very existence of such a method encourages people to write methods returning anything. This is surely no good practice, as being strict helps to prevent errors. That's why I'm quite sure there's no such method in Guava.

Maybe my answer should better be a comment, but it's too long and I don't think there'll be a positive answer, anyway.

更多推荐

本文发布于:2023-07-24 20:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1250532.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字   中用   对象   Object   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!