Can I access new methods in anonymous inner class with some syntax?

前端 未结 7 2215
深忆病人
深忆病人 2020-12-01 14:48

Is there any Java syntax to access new methods defined within anonymous inner classes from outer class? I know there can be various workarounds, but I wonder if a special sy

7条回答
  •  一向
    一向 (楼主)
    2020-12-01 14:53

    The right way to do it is using reflection:

    import java.lang.reflect.InvocationTargetException;
    
    public class MethodByReflectionTest {
    
        public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
    
            Object obj = new Object(){
                public void print(){
                    System.out.println("Print executed.");
                }
            };
    
            obj.getClass().getMethod("print", null).invoke(obj, null);
        }  
    }
    

    You can check here: How do I invoke a Java method when given the method name as a string?

提交回复
热议问题