Java 8 forEach cannot be resolved to a variable - java-8

I wanted to learn the differences between Java 8 and Java 7. At the moment I am looking into the Java 8 forEach loop.
public class Main {
public static void main(String[] args){
List<String> strings = Arrays.asList("hello","my","name","is","test");
strings.stream().forEach(s -> System.out.println(s));
}
}
This code is generating the following error for me:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
s cannot be resolved to a variable
Syntax error on token "-", -- expected
s cannot be resolved to a variable
at Main.main(Main.java:7)
I am sure that the JDK aswell as the JRE are Java 8, since the compuler can recognize the forEach method from the List but not the -> parameter.

I fixed this problem by reinstalling the JRE, JDK and created a completely new installation of eclipse.
Apparently the old eclipse was still linked to some leftovers from a Java 7 JDK.

Test you java version in command prompt
c:> java -version
If it gives 1.7 then your JDK is not updated to 1.8.
In eclipse you can windows->preferences->java->compiler and select compiler compliance level as 1.8

Related

Use withType() for configuring Gradle task not compiling in IntelliJ

I'm trying to configure the Test task inside a custom Gradle plugin written in Java.
Applying the plugins I need like so in build.gradle.kts:
plugins {
`java-gradle-plugin`
`maven-publish`
}
I can compile the code successfully through the command line as in ./gradlew clean build
But, IntelliJ complains about Test.class in the following code:
public static void configureTesting(final Project project) {
project.getTasks().withType(Test.class).configureEach(task -> {
});
}
Saying:
Required type: java.lang.Class <S>
Provided: java.lang.Class <Test>
reason: no instance(s) of type variable(s) exist so that T conforms to Task
I import the Test class like this:
import org.gradle.api.tasks.testing.Test;
Gradle version: 6.7.1
IntelliJ: 2020.2.3
I spent some (a lot of) time googling this. Eventually I found a comment somewhere saying that one could try to use the internal SDK (jbr) that ships with IntelliJ instead of a manually downloaded SDK. That made it work. The internal SDK is Java 11 and I've also installed the latest version of Java 11 from Oracle. Even though they are both Java 11, the internal SDK (jbr) is working as it should, but not the external SDK. For other projects the external SDK is working fine, but not for building a Gradle plugin.

SonarQube doesn't work with Intellij Community 2019.2

I'm using SonarLint 4.1.1.3345 with IntelliJ Community 2019.2 version by binding project to our SonarQube (with SonarJava 5.3 (build 13828)installed) server. However, I got error with below stack trace from SonarLint log:
Java Main Files AST scan
60 source files to be analyzed
Unable to create symbol table for : C:\Users\username\SomeFile.java
java.lang.IllegalArgumentException: Unsupported class file major version 55
at org.objectweb.asm.ClassReader.<init>(ClassReader.java:166)
at org.objectweb.asm.ClassReader.<init>(ClassReader.java:148)
at org.objectweb.asm.ClassReader.<init>(ClassReader.java:136)
at org.sonar.java.resolve.BytecodeCompleter.loadClass(BytecodeCompleter.java:204)
at org.sonar.java.resolve.Symbols.<init>(Symbols.java:176)
at org.sonar.java.resolve.SemanticModel.createFor(SemanticModel.java:59)
at org.sonar.java.model.VisitorsBridge.visitFile(VisitorsBridge.java:110)
at org.sonar.java.ast.JavaAstScanner.simpleScan(JavaAstScanner.java:96)
at org.sonar.java.ast.JavaAstScanner.scan(JavaAstScanner.java:68)
at org.sonar.java.JavaSquid.scanSources(JavaSquid.java:116)
at org.sonar.java.JavaSquid.scan(JavaSquid.java:110)
at org.sonar.plugins.java.JavaSquidSensor.execute(JavaSquidSensor.java:93)
at org.sonarsource.sonarlint.core.analyzer.sensor.SensorsExecutor.executeSensor(SensorsExecutor.java:81)
at org.sonarsource.sonarlint.core.analyzer.sensor.SensorsExecutor.execute(SensorsExecutor.java:72)
at org.sonarsource.sonarlint.core.container.analysis.AnalysisContainer.doAfterStart(AnalysisContainer.java:132)
at org.sonarsource.sonarlint.core.container.ComponentContainer.startComponents(ComponentContainer.java:125)
at org.sonarsource.sonarlint.core.container.ComponentContainer.execute(ComponentContainer.java:110)
at org.sonarsource.sonarlint.core.container.storage.StorageAnalyzer.analyze(StorageAnalyzer.java:75)
at org.sonarsource.sonarlint.core.container.storage.StorageContainerHandler.analyze(StorageContainerHandler.java:82)
at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl.lambda$analyze$0(ConnectedSonarLintEngineImpl.java:152)
at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl.withReadLock(ConnectedSonarLintEngineImpl.java:344)
at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl.withReadLock(ConnectedSonarLintEngineImpl.java:334)
at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl.analyze(ConnectedSonarLintEngineImpl.java:149)
at org.sonarlint.intellij.core.ConnectedSonarLintFacade.analyze(ConnectedSonarLintFacade.java:74)
at org.sonarlint.intellij.core.SonarLintFacade.startAnalysis(SonarLintFacade.java:63)
at org.sonarlint.intellij.analysis.SonarLintAnalyzer.analyzeModule(SonarLintAnalyzer.java:97)
at org.sonarlint.intellij.analysis.SonarLintTask.analyze(SonarLintTask.java:176)
at org.sonarlint.intellij.analysis.SonarLintTask.run(SonarLintTask.java:100)
at org.sonarlint.intellij.analysis.SonarLintUserTask.run(SonarLintUserTask.java:39)
at org.sonarlint.intellij.analysis.SonarLintJobManager.lambda$runTask$1(SonarLintJobManager.java:120)
at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:169)
at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:591)
at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:537)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:59)
at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:156)
at org.sonarlint.intellij.analysis.SonarLintJobManager.lambda$runTask$2(SonarLintJobManager.java:120)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
"Unsupported class file major version 55" tells me that the class file Sonar used for code analysis is for java 11 version whereas my class was compiled with java 7 (I took the same class and ran it with javap it showed major version 51), and I don't even have java 11 installed on my system.
Because it works for my teammates. The only difference is they have lower version of IntelliJ installed. So I downloaded IntelliJ 2019.1.4 and it started working.
Could someone explain why it doesn't work with later version of IntelliJ and why the above error occurred? Thanks in advance!
This is a known limitation about classloaders in the IDE/sonarlint/plugin:
https://community.sonarsource.com/t/sonarlint-analysis-fails-on-intellij-2019-2-with-java-11-runtime/12905/3
https://jira.sonarsource.com/browse/SONARJAVA-3056
Example with SonarLint
In SonarLint IntelliJ running environment, this is more or less the
classpath hierarchy:
JDK -> IntelliJ classes -> SonarLint (+deps) [child-first] -> Java
plugin (+packaged deps) [child-first] -> Squid [parent-first]. So
imagine we analyze a class that is using a class X. If IntelliJ's
classloader happens to also use class X (same fully qualified name),
this will be used instead of the X provided in the analysis classpath,
even if they are to different copies of the class (different versions,
for example).

JNA.LoadLibrary works on JDK 1.6 but fails on JDK 1.8

I have a 32 bit DLL that I want to access using JNA (I am running Windows 10 64 bit). If I use JDK 1.6 the call to LoadLibrary passes but if I use the 32 bit version of JDK 1.8 then it fails.
The error message given in JDK 1.8 is "java.lang.UnsatisfiedLinkError: Unable to load library 'mydll': The specified module could not be found"
public interface MYDLL extends Library {
MYDLL INSTANCE = (MYDLL) Native.loadLibrary("mydll", MYDLL.class);
}

How to make jdk.nashorn.api.scripting.JSObject visible in plugin [duplicate]

This question already has answers here:
Access restriction: The type 'Application' is not API (restriction on required library rt.jar)
(22 answers)
Closed 7 years ago.
I have an Eclipse RCP that interacts with java script. Now with Java 8, nashorn is used and code that depended on org.mozilla.javascript (plug-in org.mozilla.javascript_1.7.2.v201005080400.jar) must be changed to use jdk.nashorn.api.scripting.
But when i try to use this import in Eclipse, it does not see it
import jdk.nashorn.api.scripting.JSObject;
I get the error:
Access restriction: The type 'JSObject' is not API (restriction on required library '<...>\jre\lib\ext\nashorn.jar')
How can I make it visible in the classpath at compile time?
jdk.nashorn.scripting is part of Nashorn's exposed API. Please see https://docs.oracle.com/javase/8/docs/jdk/api/nashorn/jdk/nashorn/api/scripting/JSObject.html
It appears to some Eclipse specific issue. I used Netbeans 8.0.2 to compile & run the following application and it compiled and ran as expected:
package javaapplication2;
import javax.script.*;
import jdk.nashorn.api.scripting.*;
public class JavaApplication2 {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
ScriptObjectMirror sobj = (ScriptObjectMirror)e.eval("({ foo: 33 })");
System.out.println(sobj.getMember("foo"));
}
}

How to get JUnit version

How to know which version of JUnit do I have installed on my PC?
Second question- How do I upgrade it?
This will print the version of jUnit.
java -cp <path-to-junit-folder>/junit.jar junit.runner.Version
The version that you are running depends on the classpath of the running application. It's possible to have multiple versions on the same machine, but if this is in question you can just write a test for it:
import junit.runner.Version;
class SomeTests {
void testJUnitVersion() {
assertEquals("4.8.2", Version.id());
}
}
To upgrade to a newer version of JUnit, you just have to download the new version and replace the old version with the new jar. It's as simple as that.
There isn't really a nice way to tell which version of JUnit you're currently using, unless you're using maven or something like that. In general, you can tell between
JUnit 3: if you're using the junit.framework.* classes
JUnit 4: if you're using the org.junit.* classes (the tests have #Test annotations on them)
In general, JUnit is backward compatible (JUnit 3 tests can be run under JUnit 4), but JUnit 4 is recommended.
Eclipse shows its runner version on JUnit view when you run your tests
In netbeans in the projects window, expand the test libraries folder of a project that has a test in it. It will say the version in the name of the jar file.
With JUnit 5 you can do something like this:
import java.util.ServiceLoader;
import org.junit.platform.engine.TestEngine;
import java.util.Iterator;
 
final ServiceLoader<TestEngine> loader = ServiceLoader.load(TestEngine.class);
final Iterator<TestEngine> iterator = loader.iterator();
final TestEngine testEngine = iterator.next();
final String version = testEngine.getVersion().get();
Upgrade process depends on your project structure. If it’s a Maven project, you can set the version in your pom.xml. If it’s still unclear I recommend creating another question for your specific build environment.

Resources