Search code examples
javaandroidgenericsfactory-pattern

How to write a generalized method in Factory Pattern to provide object?


public class GsonStudentFactory{
....
 public static MasterStudent createMasterStudent(Student student) {
    return gson.fromJson(student.getBody(), MasterStudent.class);
 }

 public static  BTechStudent createBtechStudent(Student student) {
    return gson.fromJson(student.getBody(), BTechStudent.class);
 }
...
}

In order to generalize I can use 'if' condition and I can check 'if instance of student is BTechStudent or MasterStudent' and return appropriate BTechStudent or MasterStudent object.

Is there any better way, to generalize these two methods?

note:- BTechStudent and MasterStudent classes extends Student class.

Thanks in Advance.


Solution

  • I'm not sure if I understood it correctly, but see if this helps you:

    public static <T extends Student> T createStudent(Student student) {
        return gson.fromJson(student.getBody(), (Class<T>) student.getClass());
    }
    

    And use it like this:

    MasterStudent masterStudent = createStudent(student);
    

    or

    BTechStudent btech = createStudent(student);