1.FactoryBuilder
package com.util;
public class FactoryBuilder {
public static Object getInstance(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Object o = new Object();
Class cls = Class.forName(className);
o=cls.newInstance();
return o;
}
}
2.Person
package com.util;
public class Person {
private String name;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3.TestClass
package com.util;
public class TestClass {
public static void main(String[] args) {
Person person = null;
try {
person = (Person) FactoryBuilder.getInstance("com.util.Person");
person.setName("ft");
person.setAge(666);
System.out.println(person);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}