在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java  網(wǎng)絡(luò)安全/ 匿名函數(shù)中的使用

匿名函數(shù)中的使用

public class Anonymousfunction {

public void test(Test test){
    Test test2 = test;
    test2.show();   // 執(zhí)行結(jié)果:這是類的 show 方法
    Method [] methods = test2.getClass().getDeclaredMethods();
    System.out.println(methods.length);
    for(Method method : methods)     // 對象里為什么只有一個 display 函數(shù)呢 ,沒有 show 函數(shù)?
        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 方法");
}

}

問題描述 就是上面的那一行注釋,是在沒想明白

回答
編輯回答
別傷我

getDeclaredMethods是列出本類聲明的方法(不包括超類的方法),你的寫法是個Test的匿名內(nèi)部類,它只聲明了display方法

2018年2月21日 07:32
編輯回答
笨小蛋
final class Anonymousfunction$1 extends Test
{
  public void display()
  {
    System.out.println("這是 Test 類的 display 方法");
  }
}

生成的內(nèi)部類如上代碼, Test test2 = test指向的是包名.Anonymousfunction$1不是Test,
public Method[] getDeclaredMethods()throws SecurityException返回 Method 對象的一個數(shù)組,這些對象反映此 Class 對象表示的類或接口聲明的所有方法,包括公共、保護(hù)、默認(rèn)(包)訪問和私有方法,但不包括繼承的方法,不包括繼承方法,所以只有display.

2018年9月3日 20:44