尝试在我的代码中执行Open-Close原理,但在Java中出现了奇怪的行为

问题描述 投票:0回答:1
public interface MainInterface {
}

@Transactional
@Service
@Qualifier("A")
@Primary
public class A implements MainInterface {

}
@Transactional
@Service
@Qualifier("B")
public interface B implements MainInterface {

}
public interface C implements MainInterface {

}
@Service
public class InterfaceFactory {
 public MainInterface getInstance(String type ) {
    if (type.equalsIgnoreCase("A") ) {
        return new A();
    } else if (type.equalsIgnoreCase("B") ) {
        return new B();
    } else if (type.equalsIgnoreCase("C") ) {
        return new C();
    }else {
     return null;
    }
    }

    }

@Service
public class EventInterceptor {

 public ADTO callEvent(A a, Entity entity) throws URISyntaxException {
  System.out.print("A"); 
}
public ADTO callEvent(B b, Entity entity) throws URISyntaxException {
System.out.print("B"); 
}
public ADTO callEvent(C c, Entity entity) throws URISyntaxException {
System.out.print("C"); 
}
public ADTO callEvent(MainInterface  m, Entity entity) throws 
URISyntaxException {
System.out.print("MainInterface  ); 
}
}

//------------ i'm calling it like so 
MainInterface  obj= interfaceFactory.getInstanceInterface("A");
     gateWayInterceptor.callEvent( obj,entity)));

它总是打印MainInterface的问题并且始终返回callEvent(MainInterface m,Entityentity),即使返回类型为A OR B OR C,这也是打开的。

我试图将其设为通用类型,但我无法我试图删除callEvent(MainInterface m,Entityentity)但出现异常我做了与该博客中的代码相同的操作https://blog.jetbrains.com/upsource/2015/08/31/what-to-look-for-in-a-code-review-solid-principles-2/关于已售出-开盘收盘原理

应该输入callEvent(A a,实体实体)而不是callEvent(MainInterface m,实体实体)

注意我正在使用Java 8

[公共接口MainInterface {} @Transactional @Service @Qualifier(“ A”)@主要公共类A实现MainInterface {} @Transactional @Service @Qualifier(“ B”)公共接口B实现...

spring spring-boot spring-mvc java-8
1个回答
0
投票
我不是主要的Java开发人员,但会假定这是因为要传递给CallEvent的obj变量被声明为MainInterface类型...请在传递时尝试对其进行强制转换,即使用“(A)obj”而不只是“ obj”,然后看看您得到了什么。
© www.soinside.com 2019 - 2024. All rights reserved.