java访问匿名类的变量

3npbholx  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(291)

是否有方法访问匿名类示例中定义的变量:

class someClass{
    returntype someMethod(){
    Thread t = new Thread(new Runnable() {
           ANrequest request;
           ANresponse response;

           @Override
           public void run() {
               request = somerequest.build();
               response = request.executeForObjectList(Myclass.class);
           }
       });
       t.start();
       t.join();
      if (this)
         return response.isSucces();
      else
         return request.something();

}
}

我发现我可以定义示例变量并在匿名类->中使用它们,但我不想这样做

class someClass{
    ANrequest request;
    ANresponse response;
    returntype someMethod(){
    Thread t = new Thread(new Runnable() {

           @Override
           public void run() {
               request = somerequest.build();
               response = request.executeForObjectList(Myclass.class);
           }
       });
       t.start();
       t.join();
      if (this)
         return response.isSucces();
      else
         return request.something();

}
}

或者我们可以在方法内部生成最后一个元素数组,然后使用它的字段来传递结果,我认为这是不好的做法。

class someClass{
    ANrequest request;
    ANresponse response;
    returntype someMethod(){

    Thread t = new Thread(new Runnable() {
           final ANrequest request[]=new Anrequest[1]; 
          final ANresponse response[]=new Anresponse[1];
           @Override
           public void run() {
               request[0] = somerequest.build();
               response[1] = request.executeForObjectList(Myclass.class);
           }
       });
       t.start();
       t.join();
      if (this)
         return response[0].isSucces();
      else
         return request[1].something();

 }
}

所以我的问题是:在匿名类中是否有定义变量的方法,然后再访问它们:
像这样:

Runnable r= new Runnable () {
           ANrequest request;
           ANresponse response;

           @Override
           public void run() {
               request = somerequest.build();
               response = request.executeForObjectList(Myclass.class);
           }
       };

稍后: r.response 或者 r.request

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题