目录

PMD - Avoid autogenerated methods to access private fields and methods of inner / outer classes

PMD错误

Avoid autogenerated methods to access private fields and methods of inner / outer classes

样例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class Test {

    public static void main(final String[] args) {
        //code
    }

    public void test(){
        Executors.newSingleThreadExecutor().execute(new Thread() {
            @Override
            public void run() {
                final int a = getNum();
                System.out.println(a);
            }
        });
    }

    private int getNum() {
        return 0;
    }
}

报错原因

在匿名内部类的方法里去调用外部类的私有方法或变量就会报这个PMD错误。

解决方法

可以将匿名内部类的方法里调用到的外部类的私有方法/变量改成protected。以样例来举例,即将getNum()的权限改为protected:

1
2
3
protected int getNum() {
    return 0;
}