想不明白的问题,有请大家帮忙解决......

wzz_boy 2007-08-11 01:02:13
Thinking in java第十一章中间有这么一个程序:
public class Groundhog
{
protected int number;
public Groundhog(int n)
{
number=n;
}
public String toString()
{
return "Groundhog # "+number;
}
};

public class Prediction
{
private boolean shadow=Math.random()>0.5;
public String toString()
{
if(shadow)
return "Six more weeks of Winter!";
else
return "Early Spring!";
}
};

import java.util.*;
import java.lang.reflect.*;
public class SpringDetector
{
public static void detectSpring(Class groundHogClass) throws Exception
{
Constructor ghog=groundHogClass.getConstructor(new Class[] {int.class});
Map map=new HashMap();
for(int i=0;i<10;i++)
map.put(ghog.newInstance(new Object[]{new Integer(i)}),new Prediction());
System.out.println("map = "+map+"\n");
Groundhog gh=(Groundhog)ghog.newInstance(new Object[]{new Integer(3)});
System.out.println("Looking up prediction for "+gh);
if(map.containsKey(gh))
System.out.println((Prediction)map.get(gh));
else
System.out.println("Key not found: "+gh);

}
public static void main(String [] args) throws Exception
{
detectSpring(Groundhog.class);
}
};


问题-:Constructor ghog=groundHogClass.getConstructor(new Class[] {int.class});这里是什么意思?特别是:new Class[] {int.class},那个int.class 是什么来的?

问题二:Groundhog gh=(Groundhog)ghog.newInstance(new Object[]{new Integer(3)});这也不懂,(new Object[]{new Integer(3)})这又是什么意思?创建的是什么东西?谢谢帮忙!!!
...全文
173 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
奋斗并快乐着 2007-08-12
  • 打赏
  • 举报
回复
(new Object[]{new Integer(3)})
---
这句生成了一个Object[]类型的数组,长度为1,里边有一个封装了3的Integer对象.
yjgoo199 2007-08-11
  • 打赏
  • 举报
回复
Groundhog gh=(Groundhog)ghog.newInstance(new Object[]{new Integer(3)});
通过前面找到的构造器ghog,执行他的newInstance方法,并指定参数为3,构造一个Groundhog 对象。
不好意思,在做其他的事,发了三帖。
树成 2007-08-11
  • 打赏
  • 举报
回复
这是java中的反射。
yjgoo199 2007-08-11
  • 打赏
  • 举报
回复
Constructor ghog=groundHogClass.getConstructor(new Class[] {int.class});
这句话的意思是建造一个构造函数,参数为int型的。
yjgoo199 2007-08-11
  • 打赏
  • 举报
回复
jdk在加载类的时候会给每个类实例一个Class对象,在程序中可以通过ClassName.class或实例.getClass();还有Class.forName(packagename.ClassName);来获取。

62,614

社区成员

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

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