Advertisement
Guest User

Untitled

a guest
Dec 11th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. https://stackoverflow.com/questions/31768610/reflection-in-factory-design-patterns-in-java-or-c-sharp
  2.  
  3. class PersonFactory {
  4. // reflection, by full qualified class name
  5. public static Person getPersonWithFullQualifiedClassName(String personType) throws Exception {
  6. Class<?> personClass = Class.forName(personType);
  7. return getPersonWithClass(personClass);
  8. }
  9.  
  10. // reflection, by passing class object
  11. public static Person getPersonWithClass(Class personClass) throws Exception {
  12. return (Person) personClass.newInstance();
  13. }
  14.  
  15. // no reflection, the ordinary way
  16. public static Person getPersonWithName(String personType) {
  17. if (personType.equalsIgnoreCase("STUDENT")) {
  18. return new Student();
  19. } else if (personType.equalsIgnoreCase("TEACHER")) {
  20. return new Teacher();
  21. }
  22.  
  23. return null;
  24. }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement