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;
}
}怎么 反射不到呢?高人指点!

解决方案 »

  1.   

    type是int型的啊,就算转换成String也还是些数字的字符串!
    你是不是忘了用个switch语句判断一下type将其转换成相应shape类型的字符串!
      

  2.   

    public class ShapeFactory {
    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();
      }
    }