如何在匿名类中访问变量?

时间:2015-06-03 04:31:34

标签: java servlets anonymous-class anonymous-inner-class

我有以下代码:

    class A  extends HttpServlet{
        protected void doGet(HttpServletRequest request, HttpServletRespons
 response) throws ServletException, IOExceptio
           {
             String str= "String In doGet()";
               JsonBatchCallback<Users> callback = new
     JsonBatchCallback<Users>(){
              String inThisClass = str; // Showing me error 
        }
     }
     }

str无法访问。我如何访问"str"

我的实际代码如下:

public class SyncTask extends HttpServlet {

    private static final long serialVersionUID = 1L;

    final  Logger logger    =   Logger.getLogger(this.getClass().getName());

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String domain        = request.getParameter("DomainName");
        String reqAdminEmail = request.getParameter("AdminEmail");
        String searchRegex   = request.getParameter("searchRegex");

        Boolean manualSync  =   false;

        if(reqAdminEmail != null){
            manualSync  =   true;
        }

        String adminEmail = "";

        try{

            Date startTime = new Date();

            Manager mangerObj = new Manager("MASTER");

            final String SERVICE_ACCOUNT_EMAIL              = Constant.getServiceAccountEmail();

            final String SERVICE_ACCOUNT_PKCS12_FILE_PATH   = Constant.getServiceAccountPkcs12FilePath();


            Collection<String> SCOPES = new ArrayList<String>();
            SCOPES.add("https://www.googleapis.com/auth/admin.directory.user");
            SCOPES.add("https://www.googleapis.com/auth/admin.directory.orgunit");


            String nextToken = null;
            int noOfUsers    = 0;

            mangerObj = new Manager(domain);

            Configuration config = mangerObj.getConfiguration();
            if(config==null)
                return;
            else
                adminEmail = config.getAdminEmail();


            HttpTransport httpTransport = new NetHttpTransport();
            JacksonFactory jsonFactory  = new JacksonFactory();

            GoogleCredential credential = new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(jsonFactory)
            .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
            .setServiceAccountScopes(SCOPES)
            .setServiceAccountUser(adminEmail)
            .setServiceAccountPrivateKeyFromP12File(
                    new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
                    .build();

            Directory directoryService = new Directory.Builder(httpTransport, jsonFactory, credential).setApplicationName("Directory ").build();
            BatchRequest batch = directoryService.batch();

            do{

                List list = directoryService.users().list();
                list.setCustomer("my_customer");
                list.setMaxResults(500);
                list.setPageToken(nextToken);
                list.setFields("nextPageToken,users(relations,orgUnitPath,primaryEmail,name)");
                if(searchRegex != null ){
                    if(searchRegex.isEmpty() == false){
                        list.setQuery("email:"+searchRegex+"*");
                    }
                }

                JsonBatchCallback<Users> callback = new JsonBatchCallback<Users>() {

                    @Override
                    public void onSuccess(Users users, HttpHeaders responseHeaders) {
                        nextToken = users.getNextPageToken(); // i'm not able to access  nextToken
                    }

                    public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
                        System.out.println("Error Message: " + e.getMessage());
                    }
                };

                list.queue(batch, callback);

            }while(nextToken != null);

            try {
                batch.execute();
            } catch(Exception ex){
                ErrorHandler.errorHandler(this.getClass().getName(), ex);
            }

        }catch(Exception ex){
            ErrorHandler.errorHandler(this.getClass().getName(), ex);
        }

    }

我已经更新了我的代码,实际上我遇到了错误。我想访问nextToken进入匿名类,但我无法访问。

错误如下:

nextToken cannot be resolved to a variable

2 个答案:

答案 0 :(得分:1)

您需要制作str变量final

事实上inThisClass变量是多余的,至少在你发布的内容中是这样。

但您的实际代码会显示示例代码中的其他错误消息。您的实际代码无法写入,因为您没有对来自匿名类的封闭范围内的局部变量进行写访问。您将不得不考虑其他内容,例如final StringBuilder.

答案 1 :(得分:0)

将doGet中的str声明为final

final String str = "String In doGet()";

匿名类只能访问外部方法的最终局部变量。在Java 8中它被改变了。 此外,您的IDE应该可以帮助您修复此类错误。