为了账号安全,请及时绑定邮箱和手机立即绑定

匿名函数中的使用

匿名函数中的使用

慕田峪7331174 2019-02-20 08:20:20
public class Anonymousfunction { public void test(Test test){ Test test2 = test; test2.show(); // 执行结果:这是类的 show 方法 Method [] methods = test2.getClass().getDeclaredMethods(); System.out.println(methods.length); for(Method method : methods) // 对象里为什么只有一个 display 函数呢 ,没有 show 函数? System.out.println(method.getName()); } public static void main(String [] args){ Anonymousfunction anonymousfunction = new Anonymousfunction(); anonymousfunction.test(new Test (){ public void display () { System.out.println("这是 Test 类的 display 方法"); } }); } } class Test{ public void show(){ System.out.println("这是类的 show 方法"); } } 问题描述 就是上面的那一行注释,是在没想明白
查看完整描述

2 回答

?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

getDeclaredMethods是列出本类声明的方法(不包括超类的方法),你的写法是个Test的匿名内部类,它只声明了display方法

查看完整回答
反对 回复 2019-03-01
?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

final class Anonymousfunction$1 extends Test
{
  public void display()
  {
    System.out.println("这是 Test 类的 display 方法");
  }
}

生成的内部类如上代码, Test test2 = test指向的是包名.Anonymousfunction$1不是Test,
public Method[] getDeclaredMethods()throws SecurityException返回 Method 对象的一个数组,这些对象反映此 Class 对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法,不包括继承方法,所以只有display.

查看完整回答
反对 回复 2019-03-01
  • 2 回答
  • 0 关注
  • 431 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号