反射的问题

结贴是美德 2012-02-14 03:59:26

package reflection;

import java.lang.reflect.Constructor;

public class Test {


public static void main(String[] args) {
Class<String> cl = String.class;//正确
Class<String> cl1 = new String().getClass(); //错误
Class<? extends String> cl2 = new String().getClass();//只能这样
}

}


String.class和new String().getClass()搞不清除了。。。求指教
...全文
133 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
xuchongzhigmail 2012-02-15
  • 打赏
  • 举报
回复
反射一直没学好
SmarkMeng 2012-02-14
  • 打赏
  • 举报
回复
不是很了解 回去好好查查
结贴是美德 2012-02-14
  • 打赏
  • 举报
回复
getClass()还是final的。。这不太像是动态绑定吧。。
结贴是美德 2012-02-14
  • 打赏
  • 举报
回复
Object中定义的getClass()方法的返回值类型是Class<?>。。任何子类中也没重载,这Class<? extends String>貌似是编译器附加了一个要求

API看的也是云里雾里:

public final Class<?> getClass()
Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.
The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:

Number n = 0;
Class<? extends Number> c = n.getClass();

Returns:
The Class object that represents the runtime class of this object.
See Also:
Literals, section 15.8.2 of The Java™ Language Specification.
MiceRice 2012-02-14
  • 打赏
  • 举报
回复
可以简单点理解为Java的编译器还不够聪明,编译期间无法智能识别出下面两者的差异:

Class<? extends Object> cl2 = new Object() {private int a = 0;}.getClass();

Class<? extends Object> cl2 = new Object().getClass();

所以只好一视同仁的按照前者处理了。
结贴是美德 2012-02-14
  • 打赏
  • 举报
回复
不是很明白哎。。
安特矮油 2012-02-14
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 hongjn 的回复:]
Class<String> cl1 = new String().getClass(); //错误

因为你new一个对象,在编译时期无法确定你new的是什么对象,只能说你new的对象必须是String或者String的子类,虽然String类final的,其他类同理。

所以 Class<? extends String> cl2 = new String().getClass();//……
[/Quote]
楼上兄弟说的是对的,因为java有动态绑定这样一个特性
hongjn 2012-02-14
  • 打赏
  • 举报
回复
Class<String> cl1 = new String().getClass(); //错误

因为你new一个对象,在编译时期无法确定你new的是什么对象,只能说你new的对象必须是String或者String的子类,虽然String类final的,其他类同理。

所以 Class<? extends String> cl2 = new String().getClass();//只能这样

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧