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

前端 未结 7 2219
深忆病人
深忆病人 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 15:12

    A student in my class asked our professor if this could be done the other day. Here is what I wrote as a cool proof of concept that it CAN be done, although not worth it, it is actually possible and here is how:

    public static void main(String[] args){
    
        //anonymous inner class with method defined inside which
        //does not override anything
        Object o = new Object()
        {
            public int test = 5;
            public void sayHello()
            {
                System.out.println("Hello World");
            }
        };
    
        //o.sayHello();//Does not work
    
        try 
        {
            Method m = o.getClass().getMethod("sayHello");
            Field f = o.getClass().getField("test");
            System.out.println(f.getInt(o));
            m.invoke(o);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    

    By making use of Java's Method class we can invoke a method by passing in the string value and parameters of the method. Same thing can be done with fields.

    Just thought it would be cool to share this!

提交回复
热议问题