weixin_45492256 2022-01-03 22:38 采纳率: 100%
浏览 37
已结题

如何实例化这个匿名内部类

package com.lzw;

public class AnonymityInnerClass {
}
class OuterClass4{

public OutInterface doit(final String s){
    return new OutInterface(){
        private int i=0;
        public int getValue(){
            System.out.println(s);
            return i;
            
        }
        public void f(){
            System.out.println("f()");
        }
    };
}

}
interface OutInterface { // 定义一个接口
}

  • 写回答

2条回答 默认 最新

  • 日落西风又在吹 2022-01-04 10:03
    关注
    1. 以上代码直接调用方法会导致找不到方法,因为父类没有子类(匿名内部类)方法,所以无法直接声明式调用
    2. 以下代码使用反射形式进行方法调用
      ```java

    import java.lang.reflect.Method;
    public class AnonymityInnerClass {
    }
    class OuterClass4 {
    /**
    * 测试调用内部类方法
    * @param args
    * @throws Exception
    */
    public static void main(String[] args) throws Exception {
    OutInterface doit = new OuterClass4().doit("123123");
    // 反射获取getValue方法
    Method getValueMethod = doit.getClass().getMethod("getValue");
    // 执行getValue具体方法
    getValueMethod.invoke(doit);
    // 反射获取f方法
    Method fMethod = doit.getClass().getMethod("f");
    // 执行f具体方法
    fMethod.invoke(doit);
    }

    public OutInterface doit(final String s) {
        return new OutInterface() {
            private int i = 0;
            public int getValue() {
                System.out.println(s);
                return i;
            }
            public void f() {
                System.out.println("f()");
            }
        };
    }
    

    }
    interface OutInterface {
    }
    ```

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 1月12日
  • 已采纳回答 1月4日
  • 创建了问题 1月3日

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度