panel.properties代码:1=Circle;
2=Rectangle;
3=Line;Shape代码:package exercice01;public interface Shape {
    abstract void draw();
}Circle代码(Line、Rectangle 类似):package exercice01;public class Circle implements Shape {    @Override
    public void draw() {
        System.out.println("Circle!");
    }}ShapeFactory代码:package exercice01;import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;public class ShapeFactory {
    private static Properties shape = new Properties();
    static {
        InputStream in = ShapeFactory.class.getResourceAsStream("/panel.properties");
        try {
            shape.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static Shape getShape(int type) {
        String className = (String)shape.get(String.valueOf(type));
        String fullName = "exercice01."+className;
        System.out.println("fullName:" + fullName);
        Shape theShape = null;
        try {
            theShape = (Shape) Class.forName(fullName).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return theShape;
    }}
Panel代码:package exercice01;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;public class Panel {    public static void selectShape() throws NumberFormatException, IOException {
        System.out.println("input the type:");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int shapeType = Integer.parseInt(br.readLine());
        Shape shape = ShapeFactory.getShape(shapeType);
        if(shape == null) {
            System.out.println("null");
        } else {
            shape.draw();
        }
    }
    
    public static void main(String[] args) {
        try {
            new Panel().selectShape();
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }}
运行结果:
如果把ShapeFactory中theShape = (Shape) Class.forName(fullName).newInstance();改为theShape = (Shape) Class.forName(“exercice01.Line”).newInstance();,运行结果不报错,如下:
可是前一种情况fullName的值就是“exercice01.Line”(打印出来也是“exercice01.Line”),为什么找不到类?