一个关于Class类的小小疑惑
class Rect { double width,height,area;
public double getArea()
{ area=height*width;
return area;
}
}
public class Boy
{ public static void main(String args[])
{ try{ Class cs=Class.forName("Rect");
Rect rect=(Rect)cs.newInstance();
rect.width=100;
rect.height=200;
System.out.println("rect的面积"+rect.getArea());
}
catch(Exception e){}
}
}
此程序运行没有结果 求解释?? eclipse坏境中
----------------解决方案--------------------------------------------------------
这个程序有一个不好的习惯,要不然问题自己可以找到。
try
{
Class cs = Class.forName("j1030.Rect");
Rect rect = (Rect) cs.newInstance();
rect.width = 100;
rect.height = 200;
System.out.println("rect的面积" + rect.getArea());
}
catch (Exception e)
{
e.printStackTrace();
}
1.注意红色第二处,无论如何既然你要catch异常,说明你要处理,要不然就抛出来。
2.注意红色第一处,Class cs = Class.forName("j1030.Rect");,这个类它需要一个类的全路径名,也就是包名加类名。
----------------解决方案--------------------------------------------------------
谢啦,是我大意了
----------------解决方案--------------------------------------------------------