How to get a reference to Modifier.PUBLIC that can not be applied in builder in MethodSpec's methodBuilder for JavaPoet

喜欢而已 提交于 2020-01-25 03:36:09

问题


Attempting to implement the basic JavaPoet example (see below) in a Android ActivityWatcher class from LeakCanary:

.addModifiers(Modifier.PUBLIC, Modifier.STATIC)

The Modifier.PUBLIC and Modifier.STATIC, and the other .addModifiers statement produce the Android Studio error

addModifiers (javax.lang.model.element.modifier...) in Builder can not be applied to (int, int)

and the following gradle error:

:Machine-android:compileDebugJava

C:\AAAMachine\Machine-master\Machine-android\src\main\java\com\bmp\ActivityWatcher.java:58: error: cannot access Modifier .addModifiers(Modifier.PUBLIC, Modifier.STATIC) ^ class file for javax.lang.model.element.Modifier not found C:\AAAMachine\Machine-master\Machine-android\src\main\java\com\bmp\ActivityWatcher.java:65: error: method addModifiers in class Builder cannot be applied to given types; .addModifiers(Modifier.PUBLIC, Modifier.FINAL) ^ required: Modifier[] found: int,int reason: varargs mismatch; int cannot be converted to Modifier C:\AAAMachine\Machine-master\Machine-android\src\main\java\com\bmp\ActivityWatcher.java:73: error: cannot access Filer javaFile.writeTo(System.out); ^ class file for javax.annotation.processing.Filer not found C:\AAAMachine\Machine-master\Machine-android\src\main\java\com\bmp\ActivityWatcher.java:172: error: method addModifiers in class Builder cannot be applied to given types; .addModifiers(Modifier.PUBLIC, Modifier.STATIC) ^ required: Modifier[] found: int,int reason: varargs mismatch; int cannot be converted to Modifier C:\AAAMachine\Machine-master\Machine-android\src\main\java\com\bmp\ActivityWatcher.java:179: error: method addModifiers in class Builder cannot be applied to given types; .addModifiers(Modifier.PUBLIC, Modifier.FINAL) ^ required: Modifier[] found: int,int reason: varargs mismatch; int cannot be converted to Modifier C:\AAAMachine\Machine-master\Machine-android\src\main\java\com\bmp\ActivityWatcher.java:187: error: cannot access Path javaFile.writeTo(System.out); ^ class file for java.nio.file.Path not found Note: C:\AAAMachine\Machine-master\Machine-android\src\main\java\com\bmp\internal\MachineInternals.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 6 errors

FAILED

FAILURE: Build failed with an exception.

  • What went wrong: Execution failed for task ':Machine-android:compileDebugJava'.

    Compilation failed; see the compiler error output for details.

  • Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 6.881 secs

and here's the error from messages:

:machine-android:compileDebugJava

C:\AAAmachine\machine-master\machine-android\src\main\java\com\bmp\ActivityWatcher.java Error:(58, 15) error: cannot access Modifier class file for javax.lang.model.element.Modifier not found Error:(65, 15) error: method addModifiers in class Builder cannot be applied to given types; required: Modifier[] found: int,int reason: varargs mismatch; int cannot be converted to Modifier Error:(73, 19) error: cannot access Filer class file for javax.annotation.processing.Filer not found Error:(172, 15) error: method addModifiers in class Builder cannot be applied to given types; required: Modifier[] found: int,int reason: varargs mismatch; int cannot be converted to Modifier Error:(179, 15) error: method addModifiers in class Builder cannot be applied to given types; required: Modifier[] found: int,int reason: varargs mismatch; int cannot be converted to Modifier Error:(187, 19) error: cannot access Path class file for java.nio.file.Path not found Note: C:\AAAmachine\machine-master\machine-android\src\main\java\com\bmp\internal\machineInternals.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output Error:Execution failed for task ':machine-android:compileDebugJava'.

Compilation failed; see the compiler error output for details. Information:BUILD FAILED Information:Total time: 6.881 secs Information:7 errors Information:0 warnings Information:See complete output in console

Here's the gist of the source code using the basic example from the readme.md file from JavaPoet:

package com.bmp;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ViewGroup;

import com.bmp.util.eventbus.FabricLogEvent;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Modifier;

import de.greenrobot.event.EventBus;

import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
import static com.bmp.Preconditions.checkNotNull;



@TargetApi(ICE_CREAM_SANDWICH) public final class ActivityWatcher {

    public static void installOnIcsPlus(Application application, RefWatcher refWatcher) {
        if (SDK_INT < ICE_CREAM_SANDWICH) {
          // If you need to support Android < ICS, override onDestroy() in your base activity.
          return;
        }

    ActivityWatcher activityWatcher = new ActivityWatcher(application, refWatcher);
    activityWatcher.watchActivities();

    MethodSpec main = MethodSpec.methodBuilder("main")
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .returns(void.class)
            .addParameter(String[].class, "args")
            .addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!")
            .build();

    TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(main)
            .build();

    JavaFile javaFile = JavaFile.builder("com.bmp.helloworld", helloWorld)
            .build();

    try {
        javaFile.writeTo(System.out);
    } catch (IOException e) {
        e.printStackTrace();
    }

    FileWriter fileWriter = null;
    try {
        fileWriter = new FileWriter(new File("com.bmp.newclass.java"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Could it be related to the physical file name to be written?


回答1:


Change your imports to import javax.lang.model.element.Modifier. If you can’t import this package change your project’s module configuration from the Android SDK to the Java SDK.




回答2:


In your Android project, create a single Java module for code use JavaPoet.
suce as

In this module, your build.gradle file should be like this:

apply plugin: 'java'

sourceCompatibility = "1.7"
targetCompatibility = "1.7"
dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  compile 'com.squareup:javapoet:1.7.0'
}

.


回答3:


I find this way can work

this just is Android studio bug . Android studio code check error for that . add this code in your build.gradle in your moudle ,or your app module ,that error will go gone!

implementation 'org.checkerframework:checker:2.1.10'

add this one ,and the processor module will work

The whole build.gralde like this:

apply plugin: 'java-library'
repositories {
    mavenCentral()
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.squareup:javapoet:1.11.1'
    implementation 'com.google.auto.service:auto-service:1.0-rc6'
    implementation 'org.checkerframework:checker:2.1.10'

    api project(':baseAnnotation')
}

sourceCompatibility = "1.7"
targetCompatibility = "1.7"

tasks.withType(JavaCompile) {
    options.encoding = "UTF-8"
}

the important is

implementation 'org.checkerframework:checker:2.1.10'

this is caputure of my android studio show

remember only add this to your build.grale (app or moudle both work for you ) this error just code check error ,just android studio app check error

   implementation 'org.checkerframework:checker:2.1.10'
    provided project(':processAnnotation')
    annotationProcessor project(":processAnnotation")

processAnnotation is my process Module .



来源:https://stackoverflow.com/questions/34957630/how-to-get-a-reference-to-modifier-public-that-can-not-be-applied-in-builder-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!