有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java访问匿名内部类中的本地方法变量,该类具有同名变量

我有两个同名的变量,一个在方法中,另一个在该方法内部的匿名内部类中。如何访问匿名类中的方法1而不需要重命名它们中的任何一个

public void doSomething() {
   final String s = "method string";
   new Runnable() {
      public void run() {
         String s = "anonymous inner class string";
         // how can I access the method string here without the need to rename any of the variables
      }
   };
}

我知道这可以通过重命名任何变量来解决,但我想知道是否有更聪明的方法


共 (1) 个答案

  1. # 1 楼答案

    如果不想重命名任何变量,那么可以创建另一个方法来访问method string变量。像这样:

    final String s = "method string";
    Runnable runnable = new Runnable() {
        public void run() {
            String s = "anonymous inner class string";
            String outerS = getS();
            System.out.println(outerS);
            System.out.println(s);
            // how can I access the method string here without the need to rename any of the variables
        }
    
        public String getS() {
            return s;
        }
    }; 
    

    这里创建了一个getS()方法来访问method string变量