[英]Generic type to primitive in Java 10?
How do you convert generic type "t" to Integer in the following code?如何在以下代码中将泛型类型“t”转换为 Integer?
Is ( Integer.parseInt(String.valueOf(t)
) better than explicit cast (Integer)t
? (
Integer.parseInt(String.valueOf(t)
) 比显式转换(Integer)t
更好吗?
Has Java 10 got it? Java 10 得到了吗?
import java.lang.System;
class A {
public void setString(String s) {
s += ", World!";
System.out.println ("setString:" + s);
}
public void setInt(Integer i) {
i *= 100;
System.out.println ("setInt:" + i);
}
public <T> void Method(T t)
{ if (t.getClass().getName() == "java.lang.String") {
setString(String.valueOf(t));
}
else if(t.getClass().getName() == "java.lang.Integer") {
setInt (Integer.parseInt(String.valueOf(t) ));
}
System.out.println (t.getClass().getName());
}
}
Is (Integer.parseInt(String.valueOf(t)) better than explicit cast (Integer)t
No. This is unnecessarilly complex and the cast is the way to go (this line converts the Integer to a String, and then the String to an int. This has no advantages over just casting to Integer).不。这是不必要的复杂,并且强制转换是要走的路(此行将整数转换为字符串,然后将字符串转换为整数。这与仅转换为整数相比没有优势)。
Additionnally, to operator instanceof
is much better than using getClass().getName()此外,操作符
instanceof
比使用 getClass().getName() 好得多
Your approach with converting values looks like this:您转换值的方法如下所示:
Integet t = 2;
Integer newValue = Integer.parseInt(String.valueOf(t));
So it goes as : Integer > String > Integer.所以它是:整数>字符串>整数。
As proposed by @andy-turner checking by instanceOf is simpler.正如@andy-turner 所提议的那样,instanceOf 的检查更简单。 If your class is of type X, then you can do a simple casting, without any additional methods.
如果你的类是 X 类型,那么你可以做一个简单的转换,不需要任何额外的方法。
Secondly code looks much cleaner:其次代码看起来更干净:
public <T> void method(T t) {
if (t instanceof String) {
setString((String) t); // t is an String
} else if (t instanceof Integer) {
setInt((Integer) t); // t is an Integer
}
System.out.println(t.getClass().getName());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.