Simple compilation fails under Maven, succeeds with javac - java

I have a simple Maven project that includes one file, App.java, containing
package com.foo;
public class App
{
private Long wrapper;
public long getlong() {
if (null != wrapper) {
return wrapper;
} else {
return 0;
}
}
}
(You can duplicate this by using the Maven in 5 minutes project creation and replacing App.java with the above).
mvn compile produces
.../foo/App.java:[9,12] incompatible types
found : java.lang.Long
required: long
while navigating to the directory and running javac App.java produces no errors. Anybody know what's up? (I assume that Maven uses whatever version of Java is installed on my box; in any case, that's 1.6.0_21. Thanks.

It is probably compiling with a source or target version of 1.4. You will need to configure the compiler plugin to compile for a higher version. See "How do I set up Maven so it will compile with a target and source JVM of my choice?" and "Setting the -source and -target of the Java Compiler":
...
<build>
...
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
...
</build>
...

Related

Migrating maven project to modules - ignore module-info.java

We're currently migrating to JPMS setting up module-info.java for all modules in a maven multi-module project.
For us it would be ideal to have module-info.java already reside in "dev" branch but not affecting any builds. So idea is to exclude module-info.java by default and include it only in specific maven profiles.
Does that make sense?
Anyway, doesn't work for me, module-info.java is picked up even though in excludes section as follows:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${version.maven-compiler-plugin}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<release>${maven.compiler.release}</release>
<compilerArgs>
<arg>-Xlint:${maven.compiler.warningsToIgnore}</arg>
</compilerArgs>
<excludes>
<exclude>**/module-info.java</exclude>
</excludes>
</configuration>
</plugin>
Any ideas?
PS: Idea was taken from How to exclude module-info.java in Netbeans (11)?
Still it's intersting that filter doesn't work for module-info.java, but looking the source of compiler plugin I guess that's just the way it is:
https://github.com/apache/maven-compiler-plugin/blob/master/src/main/java/org/apache/maven/plugin/compiler/CompilerMojo.java
protected void preparePaths( Set<File> sourceFiles )
{
//assert compilePath != null;
File moduleDescriptorPath = null;
boolean hasModuleDescriptor = false;
for ( File sourceFile : sourceFiles )
{
if ( "module-info.java".equals( sourceFile.getName() ) )
{
moduleDescriptorPath = sourceFile;
hasModuleDescriptor = true;
break;
}
}

Maven error with Java 8

Getting an error with Maven and Java 8 (jdk1.8.0_45). This issue does not occur with Java 7.
MCVE
Create a sample maven project. For example:
mvn archetype:create -DgroupId=testinovke -DartifactId=testinvoke
Create the following content in the generated App.java file
package testinovke;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public class App {
public static MethodHandles.Lookup lookup;
public static class Check {
public void primitive(final int i){
}
public void wrapper(final Integer i){
}
}
public static void main(String[] args) throws Throwable {
Check check = new Check();
MethodType type = MethodType.methodType(void.class, int.class);
MethodHandle mh = lookup.findVirtual(Check.class, "primitive", type);
mh.invoke();
}
}
Compile the maven project:
mvn clean compile
Output
Get the following error:
testinvoke/src/main/java/testinovke/App.java:[25,18] method invoked with incorrect number of arguments; expected 0, found 1
Tried it with both Maven 3.0.4 and 3.3.3.
This issue does not exist if I directly compile against App.java using Javac command.
Add plugin configuration for the compiler:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<verbose>true</verbose>
<fork>true</fork>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
Another solution is adding these properties:
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
to your pom.xml, and the plugins will pick these up automatically.

Error:java: javacTask: source release 8 requires target release 1.8

Using IntelliJ IDE can't compile any projects. Screenshots of settings below:
Used JDK:
Project SDK and Language level:
Language Level:
Anybody have any ideas?
Go to File > Settings > Build, Execution, Deployment > Compiler > Java Compiler If on a Mac, it's under Intellij IDEA > Preferences... > Build, Execution, Deployment > Java Compiler
Change Target bytecode version to 1.8 of the module that you are working for.
If you are using Maven
Add the compiler plugin to pom.xml under the top-level project node:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
(Hoisted from the comments.)
Note: If you don't mind reimporting your project, then the only thing you really need to do is change the pom and reimport the project, then IntelliJ will pick up the correct settings and you don't have to manually change them.
You need to go to Settings and set under the Java compiler the following:
also check the Project Settings
This looks like the kind of error that Maven generates when you don't have the compiler plugin configured correctly. Here's an example of a Java 8 compiler config.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- ... -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<!-- ... -->
</project>
The quickest way I found:
press:CTRL + SHIFT + A (For Mac ⌘ + SHIFT + A)
type: java compiler
press: ENTER
In the Settings window, set the Target bytecode to 1.8
(or 9 for java9)
There are two ways to solve this problem:
Set settings (File -> Settings -> Build, Execution, Deployment -> Java Compiler):
Add a build section to your pom.xml:
Many answers regarding Maven are right but you don't have to configure the plugin directly.
Like described on the wiki page of the Apache Maven Compiler Plugin you can just set the 2 properties used by the plugin.
<project>
[...]
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
[...]
</project>
I fixed this by going to Project Structure -> Modules, find the module in question, click on Dependencies tab, change Module SDK to Project SDK.
I fixed it just by changing target compile version to 1.8. Its in:
File >> Settings >> Build, Execution, Deployment >> Compiler >> Java Compiler
You need to go to the /.idea/compiler.xml and change target to required jdk level.
In my case I fixed this issue by opening .iml file of project (it is located in project root folder and have name same as the name of project) and changing line <orderEntry type="jdk" jdkName="1.7" jdkType="JavaSDK" /> to <orderEntry type="jdk" jdkName="1.8" jdkType="JavaSDK" />
I had everything configured as in others answers here but by some reason Idea updated .iml file incorrectly.
I fixed it by modify my POM file. Notice the last comment under the highest voted answer.
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
The source must matches the target.
I just re-import maven button, then the error disappeared.
In your Gradle app level file >> compileOptions add this two lines
android {
compileOptions {
...
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
...
}
}
If you are working with Android-studio 1.3, Follow the below steps -
Go to File - Project Structure
Under modules- app-Properties tab, choose
Source Compatibility -1.8 and
Target Compatibility - 1.8.
And you are good to go.
Under compiler.xml file you will find :
<bytecodeTargetLevel>
<module name="your_project_name_main" target="1.8" />
<module name="your_project_name_test" target="1.8" />
</bytecodeTargetLevel>
and you can change the target value from your old to the new for me i needed to change it from 1.5 to 1.8
With Intellij, using Maven, you must check that Intellij has auto-imported your project.
You can check by clicking on the Maven tab on the right of your Editor.
If your Project is not here, then add the pom.xml file by clicking on +.
Obviously, the project must also have the relevant <build/> :
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
I've just spent a while struggling with the same problem.
The only thing that worked for me was not using the built mvn (3.3.9) but pointing it to an external downloaded version (3.5.0). Finally the project opened and everything was good.
Don't forget to set dependencies for your module:
This issue occurs if your module is configured with Annotation processor and other module is not.Set the same configuration for all the modules as it wold be cyclic dependency.
the below code working fine by my side. I just add it in the pom.xml file.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
For me, the problem was about Maven not able to find proper configurations, since these items were specified in parent pom.
Changing File -> Settings -> Build, Excecution, Deployment -> Maven -> User Settings file to point to my custom settings with proper repositories fixed the problem that was otherwise hiding.
Found out about the problem through Help -> Show log in explorer -> clicking the log file, when previously only got the error in the title and "java.lang.NullPointerException" in the console.
If none of the other answers work, check your Module SDK.
I had this error pop up for me after I had updated the project SDK to 1.8, the Javac compiler to 1.8, etc. The setting that was the problem for me was the "Module SDK".
(on Linux) Go to File > Project Structure... then in the window that opens, select Modules under Project Settings. Select the module in question from the list and then the Dependencies tab and make sure that Module SDK is set appropriately.
I have checked all of the above but the error still occurs.
But reimport all maven Projects (reload button inside Maven Projects panel) works in my case.
The only thing that helped me was to delete .idea/compiler.xml file.
Solution of the problem is very simple.You have to open .idea/compiler.xml file on your İdea Project and
You should write appropriate target version

How to use older version of Java (not the default) with Maven project on NetBeans 8

I need to use Java 6 but NetBeans is not using it even after all the configurations I made. It keeps running Maven with the Default that is Java 8 for my IDE. The same configuration runs well on Eclipse so I don't get what I am doing wrong.
I don't want to define the compiler in the nb-configuration.xml since I would have to commit the file. I would expect NetBeans to get it right from the POM.
General information:
I am using NetBeans 8.0.1 (fully updated) running on Java 8
NetBeans 8 needs JDK 7+ in order to work
Using Maven 3.2.3, but the embedded (Maven 3.0.5 didn't work as well)
All Maven plugins are up to date
To reproduce simply create a Maven project of any type in NetBeans. In my case I tried with Java, Web and EJB but none worked.
The following image shows that the JDK is properly added to the IDE.
Tools > Java Platforms
JDK 1.6 is added.
POM configurations that I have tried:
Properties
<properties>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
</properties>
Compiler Plugin
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
Enforcer Plugin
Enforcing Java 6 gives the following error:
Detected JDK Version: 1.8.0-25 is not in the allowed range [1.6,1.7).
------------------------------------------------------------------------
BUILD FAILURE
Configuration for the enforcer:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>1.3.1</version>
<executions>
<execution>
<id>enforce-versions</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireJavaVersion>
<version>[1.6,1.7)</version>
</requireJavaVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
Test code for Java 6
The following code should not compile:
import java.nio.file.Files;
import java.time.LocalTime;
public class JavaVersionChecker {
public static void main(String[] args) {
System.out.println(Files.class); // Java 7 API
System.out.println("Time: " + LocalTime.now()); // Java 8 API
// Print Java version
System.out.println(System.getProperty("java.version"));
}
}
Test Output
The test code compile with Java 7 and 8 API, but only Java 6 should be accepted.
------------------------------------------------------------------------
Building java6_project 1.0-SNAPSHOT
------------------------------------------------------------------------
--- exec-maven-plugin:1.2.1:exec (default-cli) # java6_project ---
class java.nio.file.Files
Time: 19:24:05.997
1.8.0_25
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 0.610 s
Finished at: 2014-11-21T19:24:06-02:00
Final Memory: 6M/123M
------------------------------------------------------------------------
JDK 6 should be detected by the IDE
As suggested by the comments I made the configuration work using a hint property, which is also very well documented in the generated nb-configuration.xml.
Configuration added to the pom.xml:
<properties>
<netbeans.hint.jdkPlatform>JDK_1.6</netbeans.hint.jdkPlatform>
</properties>
As I understand the compile version for NetBeans needs to be set by a proprietary parameter, which is very simple to set up.
Useful nb-configuration.xml details:
Properties that influence various parts of the IDE, especially code
formatting and the like. You can copy and paste the single
properties, into the pom.xml file and the IDE will pick them up. That
way multiple projects can share the same settings (useful for
formatting rules for example). Any value defined here will override
the pom.xml file value but is only applicable to the current project.
This error was caused by an old entry in nb-configuration.xml
Just adding this property to pom.xml as suggested by #BonanzaOne did not worked for me.
By changing
<netbeans.hint.jdkPlatform>JDK_1.6.0_34</netbeans.hint.jdkPlatform>
to
<netbeans.hint.jdkPlatform>JDK_1.6</netbeans.hint.jdkPlatform>
directly in nb-configuration.xml, Netbeans picks the existing JDK 1.6 automaticaly.

Debugging Annotation processors in eclipse

I am writing a simple annotation processor and trying to debug it using eclipse. I created a new project for annotation processor and configured javax.annotation.processing.Processor under META-INF as needed and it processes annotations fine.
Then, I added some more code and tried debugging, but could never make the execution stop at the breakpoints added in the annotation processor. I am compiling using ant and I am using the following ANT options.
export ANT_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"
After triggering ant build, i go create a remote debug configuration and the debugger starts fine. Ant build also starts successfully. But the execution never stops at any break point added in the annotation processor.
This is a problem I just ran into, and the eclipse plugin solution seems super cumbersome to me. I found a simpler solution using javax.tools.JavaCompiler to invoke the compilation process. Using the code below, you can just Right-Click > Debug As > JUnit Test in eclipse and debug you annotation processor directly from there
#Test
public void runAnnoationProcessor() throws Exception {
String source = "my.project/src";
Iterable<JavaFileObject> files = getSourceFiles(source);
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
CompilationTask task = compiler.getTask(new PrintWriter(System.out), null, null, null, null, files);
task.setProcessors(Arrays.asList(new MyAnnotationProcessorClass()));
task.call();
}
private Iterable<JavaFileObject> getSourceFiles(String p_path) throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager files = compiler.getStandardFileManager(null, null, null);
files.setLocation(StandardLocation.SOURCE_PATH, Arrays.asList(new File(p_path)));
Set<Kind> fileKinds = Collections.singleton(Kind.SOURCE);
return files.list(StandardLocation.SOURCE_PATH, "", fileKinds, true);
}
This question has been posted over 6 years ago, however, I ran into the same problem now and still couldn't find a good answer on the Internet.
I was finally able to work out a good setup that allows me to develop an Annotation Processor, use it in compilation of another project, and debug it as needed.
The setup is like this:
Annotation Processor developed in a project with GAV:
<groupId>infra</groupId>
<artifactId>annotation-processor</artifactId>
<version>1.0-SNAPSHOT</version>
In the annotation-processor POM file I specified the following:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin.version}</version>
<configuration>
<compilerArgument>-proc:none</compilerArgument>
<source>${java.source.version}</source>
<target>${java.source.version}</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
Notice the <compilerArgument>-proc:none</compilerArgument> specification.
In the project where the annotation-processor is used, it is used during the compilation of the project. I.e. the annotation-processor is invoked during the execution of the compiler, javac. I found that in order to debug the annotation-processor execution while running javac directly, I can use the following command line:
javac -J-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=1044 -d target/classes -proc:only -processor infra.annotation.CustomizationAnnotationProcessor -cp ../annotation-processor/target/annotation-processor-1.0-SNAPSHOT.jar src\main\java\org\digital\annotationtest\MyTestClass.java
Notice the suspend=y part in the command line of javac. This tells the JVM to suspend execution until the debugger attaches to it.
In this situation, I can start the eclipse debugger by starting a Remote Java Application Debug Configuration. Configure it to use the annotation-processor project, and attach to the process on localhost and port 1044. this allows you to debug the annotation processor code. If you set a breakpoint in the init or process methods, the debugger will break.
In order to enable the same debug experience while compiling using Maven, I setup the POM file as follows:
Add a dependency to the POM where the annotation-processor is used:
<dependency>
<groupId>infra</groupId>
<artifactId>annotation-processor</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
In the same project using the annotation-processor define the following:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<fork>true</fork>
<compilerArgs>
<compilerArg>-J-verbose</compilerArg>
<compilerArg>${enableDebugAnnotationCompilerArg}</compilerArg>
</compilerArgs>
<forceJavacCompilerUse>true</forceJavacCompilerUse>
<annotationProcessorPaths>
<annotationProcessorPath>
<groupId>infra</groupId>
<artifactId>annotation-processor</artifactId>
<version>1.0-SNAPSHOT</version>
</annotationProcessorPath>
</annotationProcessorPaths>
<annotationProcessors>
<annotationProcessor>infra.annotation.CustomizationAnnotationProcessor</annotationProcessor>
</annotationProcessors>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>debugAnnotation</id>
<properties>
<enableDebugAnnotationCompilerArg>-J-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=1044</enableDebugAnnotationCompilerArg>
</properties>
</profile>
</profiles>
Notice the use of <fork>true</fork>,
and <compilerArg>${enableDebugAnnotationCompilerArg}</compilerArg>.
Also, notice the profile deinition of debugAnnotation and the definition of
the <enableDebugAnnotationCompilerArg> property.
This allows us to start a debugging session of the annotation-processor
by running mvn -P debugAnnotation package and attaching the eclipse debugger to the compiler
process the same way as described in 4 above.
The easiest way is to create an eclipse plugin and then debug it directly from eclipse.
It sound a lot harder then it is - this: https://www.youtube.com/watch?v=PjUaHkUsgzo is a 7 minute guide in youtube that can get you started.

Categories

Resources