简体   繁体   English

Java泛型

[英]Java generics

Is it possible to make a method that will take anything, including objects, Integers etc? 是否有可能制造出一种可以接受任何东西的方法,包括对象,整数等? I have a method checking the value if it is null and I was thinking perhaps it could be done with generics instead of overloading. 我有一个检查该值是否为null的方法,我在想也许可以使用泛型而不是重载来完成。 Unfortunately, trying 不幸的是,尝试

nullChecking(Class<? extends Object> value){
...
}

won't allow Integers as they extend Number not object. 不允许整数,因为它们扩展Number not object。 Is there a way? 有办法吗?

Cheers 干杯

Can't you just do nullChecking(Object value) ? 你不能只做nullChecking(Object value)吗? If you just wanna test if it's null, it will work. 如果您只想测试它是否为null,它将起作用。

I'm not sure what you are trying to do... If it's just checking if a object is null then you can simply do this: 我不确定您要做什么...如果只是检查对象是否为null则可以执行以下操作:

public static boolean nullChecking(Object obj) {
    return obj == null;
}

Since Java 1.7 you can use the methods of java.util.Objects : 从Java 1.7开始,您可以使用java.util.Objects的方法:

public static <T> T requireNonNull(T obj)
public static <T> T requireNonNull(T obj, String message)
public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier)

or just check their code. 或者只是检查他们的代码。

Actually there is a way to do this, but I wouldn't recommend it for your usage... 其实有一种方法可以做到这一点,但是我不建议您使用它。

So, here is how to do this (and warning, it circumvents compile time type checking, so you open yourself up to run-time class-cast exceptions...) 因此,这是执行此操作的方法(警告,它避免了编译时类型检查,因此您可以接受运行时类广播异常...)

Say you have a "getter" than can return multiple types - it can be declared as a generic type like so: 假设您有一个“ getter”,它可以返回多个类型-可以将其声明为通用类型,如下所示:

public <X> X get(String propertyName) { ... }

You can do the same for a 'setter': 您可以对“设置者”执行相同的操作:

public <X> void set(String property, X value) { ... }

A 一种

public <T> boolean isNull(T obj) { return obj == null; } 

would work... but... what for? 会工作...但是...为什么呢?

Do you think that 你认为

if (isNull(myObj)) { ... }

is easier to write than 比写容易

if (myObj == null) { .... }

?

Consider you will doing a method invocation in the first case and that consumes [almost nothing, but it does] system resources with no logical advantage, to me. 考虑到您将在第一种情况下进行方法调用,这对我来说几乎不消耗任何资源,但确实消耗了系统资源,而没有逻辑上的优势。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM