I came across a term called reflection. It is a feature commonly used in factory design patterns. I had a hard time understanding the concept because I’m still learning how to p
Code:
public class TestReflectionFactoryDesign {
public static void main(String[] args) throws Exception {
Person student = PersonFactory.getPersonWithFullQualifiedClassName("com.test.reflectionFactoryDesign.Student");
student.say();
Person teacher = PersonFactory.getPersonWithClass(Teacher.class);
teacher.say();
Person student2 = PersonFactory.getPersonWithName("student");
student2.say();
}
}
class Student implements Person {
@Override
public void say() {
System.out.println("I am a student");
}
}
class Teacher implements Person {
@Override
public void say() {
System.out.println("I am a teacher");
}
}
interface Person {
void say();
}
class PersonFactory {
// reflection, by full qualified class name
public static Person getPersonWithFullQualifiedClassName(String personType) throws Exception {
Class> personClass = Class.forName(personType);
return getPersonWithClass(personClass);
}
// reflection, by passing class object
public static Person getPersonWithClass(Class personClass) throws Exception {
return (Person) personClass.newInstance();
}
// no reflection, the ordinary way
public static Person getPersonWithName(String personType) {
if (personType.equalsIgnoreCase("STUDENT")) {
return new Student();
} else if (personType.equalsIgnoreCase("TEACHER")) {
return new Teacher();
}
return null;
}
}
Output:
I am a student
I am a teacher
I am a student