1.先说说为什么这两个东西会在一起
先看一个简单的工厂模式
这是一个通过字符串的形式判断该输出什么九九乘法表的
public class NineFactory {
public static void main(String[] args) {
int num = 10;
try {
NineFactory.getObject("Left").print(num);
NineFactory.getObject("Right").print(num);
NineFactory.getObject("Center").print(num);
NineFactory.getObject("What").print(num);
}catch (Exception e){
System.out.println("没有这个九九乘法表");
}
}
public static INine getObject(String string) throws Exception {
if (string.equals("Left")){
return new Left();
}else if (string.equals("Right")){
return new Right();
}else if (string.equals("Center")){
return new Center();
}
throw new Exception();
}
}
通过这个例子可以看到这种简单的工厂有许多的if语句,况且如果我们还有条件的话还需要对if语句进行修改,这样是非常麻烦的.所以我们可以用Class这个类来解决这样的问题.
2.下面我们就将工厂与反射结合起来
先看代码
public class Factory {
//通过反射构建对象,解决了工厂模式带来的耦合性,避免了new对象
public static IPrint getPrintObject(String className) throws Exception {
IPrint iPrint;
//通过Class.forName()方法来得到IPrint
iPrint = (IPrint) Class.forName(className).newInstance();
return iPrint;
}
public static INine getINineObject(String className, int num,IPrint iPrint) throws Exception{
INine iNine;
//通过Class.forName()得到INine
iNine = (INine) Class.forName(className).newInstance();
iPrint.print(num);
return iNine;
}
}
然后我们的语句就变得简单许多
public class L1_6Main {
public static void main(String[] args) throws Exception{
int num = 8;
IPrint p1 = Factory.getPrintObject("com.L1_5.ConsolePrint");
Factory.getINineObject("com.L1_3.NineCenter",num,p1).print(num);
IPrint p2 = Factory.getPrintObject("com.L1_5.FilePrint");
Factory.getINineObject("com.L1_3.NineLeft",num,p2).print(num);
}
}
2.1Class.forName()
这里我们是通过Class.forName来获取到响应的对象的,再也不用像我们传统的方式来new一个对象.我们也不需要再去修改里面的代码
注意:Class.forName(String ClassName)里面的参数是你的类的路径,也就是包名加上类名
工厂中我们用的是(“Left”),所以我们这里要写成"com.L1_3.NineLeft",我这里的Left类和NineLeft是一样的
3.总结 (获取一个类对应的Class类的方法)
1.使用Object.getClass ()方法----引用类型的对象的获取方式
如果我们已经拿到了一个对象,可以使用这个对象的 getClass 方法获得一个 Class 对象(不过这仅限于引用类型的对象):
String string=new String();
//使用已经存在的对象的getClass()方法获取Class对象
Class class1=string.getClass();
2.使用类的class成员属性
如果我们当前没有某个类的对象,无法使用 getClass() 方法来获取Class对象,那还可以使用 类名.class 来获取 Class对象:
//使用 类名.class来获取Class对象
Class class2=String.class;
其实这种方式不仅能用于引用类型,基本类型也可以。数组也是可以的:
Class class3=int.class;
Class class4=int[][].class
3.使用Class类的forName(“类完整路径”)方法获取:
如果我们有一个类的完整路径,就可以使用 Class.forName(“类完整的路径”) 来得到相应的 Class,这个方法只能用于引用类型,类的完整路径是:包名.类名
Class<?> strClass=Class.forName(“java.lang.String”);