Switch over type in java

后端 未结 8 1133
执念已碎
执念已碎 2020-12-02 14:23

Before I start, I know there are a bunch of answers to this question that suggest alternate approaches. I\'m looking for assistance to this particular approach as to whethe

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 15:05

    I was able to work around with java.lang.reflect

    import java.lang.reflect.Method;
    
    public class MyClass {
    
        public void validate(Object o) {    
            String className = o.getClass().getSimpleName();     
            try {
                //this line searches a method named as className
                Method m = this.getClass().getDeclaredMethod(className);
                //this line execute the method 
                 m.invoke(this);
            } catch (Exception e) {
                e.printStackTrace();
                handleUnknown();
            }
    
        }
    
        //this methot will execute if the object o is instance of A
        public void A() {
    
        }
        //this methot will execute if the object o is instance of B
         public void B() {
    
        }
        //this methot will execute if the object o is instance of C
         public void C() {
    
        }
        //this methot will execute if the method is unknown
        public void handleUnknown(){
    
        }
    
    
    }
    

提交回复
热议问题