想不明白的问题,有请大家帮忙解决......
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)})这又是什么意思?创建的是什么东西?谢谢帮忙!!!
------解决方案--------------------jdk在加载类的时候会给每个类实例一个Class对象,在程序中可以通过ClassName.class或实例.getClass();还有Class.forName(packagename.ClassName);来获取。
------解决方案--------------------这是java中的反射。
------解决方案--------------------(new Object[]{new Integer(3)})
---
这句生成了一个Object[]类型的数组,长度为1,里边有一个封装了3的Integer对象.