java - 决定请求类的类型?

标签 java spring jakarta-ee

我有以下三个类(class)。

SuperClass.java
SubClass1 extends SuperClass
SubClass2 extends SuperClass

我有一个方法,它将接受 SuperClass 类型的方法参数.

getResult(SuperClass request){
//Here the request can be of SubClass1 type or SubClass2 type.

}

这里是request可以是 SubClass1输入或 SubClass2类型。

内部getResult()基于请求类型的方法我需要做一些逻辑。

要找出我可以使用的类型instanceof运算符如下。

if(request instanceof SubClass1){
//do something
}else if(request instanceof SubClass2){
//dosomething
}

有没有最好的方法来找出请求的类型?

谢谢!

最佳答案

尽量避免 instanceof 关键字。

The reason instanceof is discouraged is that it's not OOP. There should be no reason for the caller/user of an object to know which concrete class it is an instance of beyond which type the variable it is declared as. If you need different behavior in subclasses add a method and implement them differently.

基本方式:我会写这样的内容:

enum Types{ SUB_1, SUB_2 }

public class SubClass1 extends SuperClass{
  public Types type = Types.SUB_1;
} 

public class SubClass2 extends SuperClass{
  public Types type = Types.SUB_2;
} 

和:

if(Types.SUB_1 == request.type){
  //do something
}else if(Types.SUB_2 == request.type){
  //do something
}

正确的方式(从我的角度来看)我会在你的情况下使用多态性。

多态性 - 发送到不同对象的相同消息会导致相关行为 接收消息的对象的性质。

意思是:

 public interface SuperClassItf{
  public void doStuff();
 }

 public class SubClass1 extends SuperClassItf{
     public void doStuff(){
          // do 1
       }
    } 

    public class SubClass2 extends SuperClassItf{
     public void doStuff(){
        // do 2
     }
    } 

主要

getResult(SuperClassItf request){
   request.doStuff(); //polymorphic method call
}

关于java - 决定请求类的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19420483/

相关文章:

java - '+' (plus sign) not encoded with RestTemplate using String url, but interpreted as ''(空格)

java - Spring Boot 指定 Hibernate 类而不是指定包

java - gson.toJson() 在 Servlet 中抛出 StackOverflowError

angularjs - AngularJS 可以在 Java EE MVC 架构 : JSP->Servlet->EJB3. 1->Business Object->DAO 中工作吗

java - 测试输入是否为整数时如何避免无限循环

java - Jaxb 编码器 setproperty XSLT 抛出 PropertyException

java - 事务需要异常 JPA/Spring

java - JPA 急切未加入

java - 如何修复折线图十字准线的位置

windows - Wildfly 10 上的 WebSocket 无法在 Windows 10 上运行