一个接口两个实现类利用反射调用不同的实现类

直接上代码

service

public interface IStudentService {

    String say(String msg);
}

两个实现类

@Service
public class AStudentServiceImpl implements IStudentService {

    @Override
    public String say(String msg) {
        return "hello my name is A" + msg;
    }
}


@Service
public class BStudentServiceImpl implements IStudentService{

    @Override
    public String say(String msg) {
        return "hello my name is B" + msg;
    }
}

枚举类

public enum StudentServiceEnum {

    aStudentServiceImpl("AImpl", "com.cache.service.AStudentServiceImpl"),
    bStudentServiceImpl("BImpl", "com.cache.service.BStudentServiceImpl");

    private String mark;
    private String path;

    StudentServiceEnum(String mark, String path) {
        this.mark = mark;
        this.path = path;
    }

    public String getMark() {
        return mark;
    }
    public void setMark(String mark) {
        this.mark = mark;
    }
    public String getPath() {
        return path;
    }
    public void setPath(String path) {
        this.path = path;
    }
}

利用反射调用

public class StudentFactory {

    public static IStudentService getService(String path) {
        try {
            return (IStudentService) Class.forName(path).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

测试

    @Test
    void test1(){
       IStudentService service = StudentFactory.getService(StudentServiceEnum.bStudentServiceImpl.getPath());
       System.out.println(service.say("aa"));
    }

猜你喜欢

转载自blog.csdn.net/weixin_44912855/article/details/115262110