我确定我的问题没有道理,但这是因为我不知道自己所看到的或如何描述...
以下代码可以很好地进行编译,但不应这样做,因为它int
与的类型不同Integer
。这不应该给编译器错误吗?如果编译器期望Class<Integer>
在运行时将其解析为Class<int>
哪种类型?这是编译器允许其使用基元的某种魔术吗?并且如果编译器放松了对原语的验证,这不会导致错误的出现,方法编写者期望该类型为EXACT类型Class<Integer>
而可以交付Class<int>
。
简而言之,为什么在运行时编译并产生correct
or wrong
(取决于透视图)结果。
public static void main(String[] args) {
printClass("int ", int.class);
printClass("Integer ", Integer.class);
System.out.printf("AreEqual", int.class == Integer.class);
}
private static void printClass(String text, final Class<Integer> klazz) {
System.out.printf("%s: %s%s", text, klazz, "\n");
}
输出:
int : int
Integer : class java.lang.Integer
AreEqual: false
对于对照组,此代码NOT COMPILE
符合我的预期
public static void main(String[] args) {
printClass("Person ", Person.class);
printClass("Employee", Employee.class);
System.out.printf("AreEqual: %s", Person.class == Employee.class);
}
private static void printClass(String text, final Class<Person> klazz) {
System.out.printf("%s: %s%s", text, klazz, "\n");
}
public class Employee extends Person {
}
public class Person {
}
错误:
Error:(8, 40) java: incompatible types: java.lang.Class<com.company.Employee> cannot be converted to java.lang.Class<com.company.Person>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句