出现Cannot refer to the non-final local variable guoDeGang defined in an enclosing scope

代码:

public interface Star {
    public void crossTalk(int money);
    public void sing(int money);
    public void acting(int money);
}
public class GuoDeGang implements Star{

    @Override
    public void crossTalk(int money) {
        System.out.println("收了"+money+"元钱,我给您说个相声");
    }

    @Override
    public void sing(int money) {
        System.out.println("收了"+money+"元钱,我给您唱歌");
    }

    @Override
    public void acting(int money) {
        System.out.println("收了"+money+"元钱,我给您演戏");
    }
    public void sleep() {
        System.out.println("郭德纲累了要睡觉");
    }

}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyDemo {

    public static void main(String[] args) {
        GuoDeGang guoDeGang = new GuoDeGang();
        ClassLoader classLoader = guoDeGang.getClass().getClassLoader();
        Class<?>[] interfaces = guoDeGang.getClass().getInterfaces();
        Star newProxyInstance =(Star) Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
            
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                
                Object invoke = method.invoke(guoDeGang, 100);
                return invoke;
            }
        });
        newProxyInstance.crossTalk(100);
        newProxyInstance.acting(100);
    
    }

}


 

在Object invoke = method.invoke(guoDeGang, 100);这个地方出现

Cannot refer to the non-final local variable guoDeGang defined in an enclosing scope报错

解决方法:提示是引用了局部变量guoDeGang出现的异常

把这行代码GuoDeGang guoDeGang = new GuoDeGang();  改为final GuoDeGang guoDeGang = new GuoDeGang();也是可以解决。

这个代码之前学习的时候敲过一次,并没有出现这样的错,所以还需要找一下原因:

找到以前代码比对了发现是两个项目路径不同,如下图:(1)的路径是之前装的eclipse版,现在已经不用,但建立的还

在被当前使用的eclispe打开并使用,重写建立的项目复制代码就没有报错了。

(1)

(2)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值