public static Shape getShape(int type) {
try {
// 获得与形状类型匹配的形状类名
String className = (String) shapes.get(String.valueOf(type));
// 运用Java反射机制构造形状对象
return (Shape) Class.forName(className).newInstance();
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
}怎么 反射不到呢?高人指点!
try {
// 获得与形状类型匹配的形状类名
String className = (String) shapes.get(String.valueOf(type));
// 运用Java反射机制构造形状对象
return (Shape) Class.forName(className).newInstance();
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
}怎么 反射不到呢?高人指点!
解决方案 »
- Windows Server 2003 Enterprise R2 - CD2 - 英文版本的序列号
- java中的String和StringBuffer传值问题,是传值还是传引用?
- 各位高手帮我看看2个方法运行结果中哪个更占内存?为什么?
- 请问this.getServletConfig()中的this是指什么啊?
- 定义一个LinkedList数组时出现NullPointerException
- 关于集合的克隆问题
- 怎样将Label.getText()的文字的一部分(如第1个字)设置成其他颜色?(100奉上)
- 一个简单的问题。书后的练习题
- 求救:如何用jbuilder解析xml文档
- 如何在JTestArea进行右对齐?
- 关于输入的问题
- 问一个大家都遇到的问题:为什么在JSP中将传进来的参数要判断是不是为空null还要判断是不是为""呢,为什么啊双重判断呢,搞不懂
你是不是忘了用个switch语句判断一下type将其转换成相应shape类型的字符串!
private static Properties shapes = new Properties();
static {
try {
InputStream in = ShapeFactory.class
.getResourceAsStream("panel.properties");
shapes.load(in); // 把配置信息加载到shapes对象中
} catch (IOException e) {
throw new RuntimeException(e);
}
} public static Shape getShape(int type) {
try {
// 获得与形状类型匹配的形状类名
String className = (String) shapes.get(String.valueOf(type));
// 运用Java反射机制构造形状对象
return (Shape) Class.forName(className).newInstance();
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
}
}是通过那个panel.properties来取的
1=Cirle
2=Line
下面是它的main方法
public class Panel {
public void selectShape()throws Exception{
System.out.println("请输入形状类型:");
//从控制台读取用户输入形状类型
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int shapeType=Integer.parseInt(input.readLine());
//获得形状实例
Shape shape=ShapeFactory.getShape(shapeType);
System.out.println("shape="+shape);
if(shape==null)
System.out.println("输入的形状类型不存在");
else
shape.draw(); //画形状
}
public static void main(String[] args)throws Exception {
new Panel().selectShape();
}
}