lundi 31 décembre 2018

I'm writing a code in java implementing reflection with factory pattern

I'm running this code but I'm getting this error message where I couldn't figure it out. It is asked to design any java code using the factory pattern with the help of reflection. plz try to help me As soon as possible. below I added the error message that appears when I run the code and btw my file name and the class name is TestReflectionFactoryDesign.

Error message:

Exception in thread "main" java.lang.ClassNotFoundException: com.test.TestReflectionFactoryDesign.Student
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at PersonFactory.getPersonWithFullQualifiedClassName(TestReflectionFactoryDesign.java:58)
    at TestReflectionFactoryDesign.main(TestReflectionFactoryDesign.java:6)

Code:

public class TestReflectionFactoryDesign {
    public static void main(String[] args) throws Exception {
        Person student = PersonFactory.getPersonWithFullQualifiedClassName("com.test.TestReflectionFactoryDesign.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;    
    }    
}





Aucun commentaire:

Enregistrer un commentaire