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

3

1

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?

Agapanthus answered 22/1, 2016 at 23:25 Comment(0)
T
3

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.

Trici answered 23/1, 2016 at 2:6 Comment(1)
Is there a way to compile this as a module within a Android project in Android Studio or is there a aar file I could use?Agapanthus
V
0

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

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'
}

the build.gradle in the java library.

Versatile answered 23/11, 2016 at 7:39 Comment(1)
Welcome to Stack Overflow! I've edited your answer. When you want to show a code snippet, it's best to show it as text. Then users can copy-paste it. To put code in code markdown, indent it by 4 spaces. Thank you for contributing, I hope your answer will be helpful!Cindy
R
0

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 .

Rizal answered 26/11, 2019 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.