你可以做Shoe
一个inner class
的ShoeFactory
:
public class ShoeFactory {
public static class Shoe {
private String name;
private Shoe() {
}
private Shoe(String name) {
this.name = name;
}
}
public static Shoe createShoe(String shoeName) {
return new Shoe(shoeName);
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这几乎涵盖了所有情况,除了...... 反思:
public class SmellyShoe {
public static void main(String[] args) {
try {
java.lang.reflect.Constructor c = Shoe.class.getDeclaredConstructors()[0];
c.setAccessible(true);
Shoe smelly = (Shoe)c.newInstance(null);
// grr
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)