I'm trying to use AST parser in a non-plugin environment. The code compiles, but I get the following runtime error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/core/resources/IResource
at org.eclipse.jdt.core.dom.ASTParser.(ASTParser.java:189)
at org.eclipse.jdt.core.dom.ASTParser.newParser(ASTParser.java: 118)
Here is the code I'm running:
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.dom.*;
public class TestAST
{
private void runTest()
{
String helloStr ="\n"+
"public class HelloWorld {\n"+
"\n"+
" private String name=\"\"\n\n"+
" /**\n"+
" * \n"+
" */\n"+
" public void sayHello() {\n"+
" System.out.println(\"Hello \"+name+\"!\");\n"+
" }\n"+
"\n"+
"}";
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(helloStr.toCharArray());
parser.setResolveBindings(true);
ASTNode tree = parser.createAST(null);
tree.toString();
}
public static void main(String args[])
{
TestAST ast = new TestAST();
ast.runTest();
}
}
Does anyone know why this is happening?
Thanks in advance,
Shirley
I recently ran into a similar issue and I slowly stepped through fixing one dependency at a time and here is the list of required dependencies that I came up with. I hope this saves some time for people who try to do this same task:
List (which matches picture below):
ContentType (org.eclipse.core.contenttype)
Jobs (org.eclipse.core.jobs)
Resources (org.eclipse.core.resources)
Runtime (org.eclipse.core.runtime)
Equinox Common (org.eclipse.equinox.common)
Equinox Preferences (org.eclipse.equinox.preferences)
JDT (org.eclipse.jdt)
JDT Core (org.eclipse.jdt.core)
OSGI (org.eclipse.osgi)
OSGI Services (org.eclipse.osgi.services)
OSGI Util (org.eclipse.osgi.util)
All these JARs will likely already be contained in your Eclipse plugins directory and you can find and add them to the build path by adding them as external JARs.
The IResource class is not on your classpath when you start the application.
If you're not using Eclipse (or some other tool) to manage the dependencies, you're going to have to track down every jar file that the Abstract Syntax Tree classes require and manually include them on your classpath. I'm not sure exactly how many this might be, but Eclipse is made up of many dozens of plugins, and manually working out the build dependencies will be a chore.
Edit: To add IResorce to the classpath, the particular jar file you're looking for will be called something like org.eclipse.core.resources_3.5.0.v20090512.jar, depending on your version of Eclipse. But I don't think it will be the only one you'll need...
I had the same problem. I solved adding the jars into the required dependencies of the the plugin.xml. You can find it in the tab Dependencies of the plugin.xml file.
Related
So right now I have two classes, one of which creates an object out of another class:
import java.io.*;
public class PostfixConverter {
public static void main(String args[]) throws IOException, OperatorException {
...
String postfixLine;
while ((postfixLine = br.readLine()) != null) {
// write some gaurd clauses for edge cases
if (postfixLine.equals("")) {
...
Cpu cpu = new Cpu();
and
public class Cpu {
Cpu() {
// this linkedListStack is for processing the postfix
...
}
Currently I'm running javac PostfixConverter.java to compile the class but it cannot find the Cpu symbol. What can I do so that the compiler can discover the missing symbol? Shouldn't everything by default be packaged in the default package and therefore find each other?
javac PostfixConverter.java
This command should work if both files are located on the current directory, as the default classpath (-cp option) is the current directory (.).
You should compile both files, so that the Cpu class file will be available to PostfixConverter:
javac Cpu.java PostfixConverter.java
Keep in mind that in general it is not desirable to build an application where everything sits in the default package. Consider creating an appropriate package here. Also, you may want to use either an IDE and/or Maven, which would make the build process easier for you.
As the other answer mentions, Java will also automatically build all Java source files in the current directory, which might explain why other source files are also getting built.
I am unable to use swing library with my scala-sdk-2.12.4.
I am using Java 9 version.
When I try to run the program:
package rs.ac.bg.etf.zd173013m.gui
import swing._
object HelloWorld extends SimpleSwingApplication {
def top = new MainFrame {
title = "First Swing App"
contents = new Button {
text = "Click me"
}
}
}
I get the following error:
Exception in thread "main" java.lang.IncompatibleClassChangeError: Method scala.swing.Reactor.$init$()V must be InterfaceMethodref constant
at scala.swing.SwingApplication.<init>(SwingApplication.scala:4)
at scala.swing.SimpleSwingApplication.<init>(SimpleSwingApplication.scala:13)
at rs.ac.bg.etf.zd173013m.gui.HelloWorld$.<init>(Application.scala:5)
at rs.ac.bg.etf.zd173013m.gui.HelloWorld$.<clinit>(Application.scala)
at rs.ac.bg.etf.zd173013m.gui.HelloWorld.main(Application.scala)
You have incompatible JAR versions on your classpath. The code in the JAR containing "SwingApplication" was compiled against a different version of "Reactor" than the one on your classpath.
What are you using to manage your dependencies? I guess that you are downloading them manually.
Switch to a dependency management system like Gradle and this problem should go away, as it will ensure that all your dependencies are consistent.
I'm doing a processing based project with eclipse and Procliping. When I'm testing the project with "Run" command inside the IDE, everything works fine. But if I export it into a runable-jar, when I run the jar it'll give this error on the line String[] li=Serial.list();. Any idea what's going wrong?
Java source attachment is "processing-2.2.1/modes/java/libraries/serial/src"
And here is a sample code:
package abcd;
import processing.core.PApplet;
import processing.serial.Serial;
public class TestUI extends PApplet {
Serial port;
public void setup(){
System.out.println(Serial.list());
}
public void draw(){
}
public static void main(String _args[]) {
PApplet.main(new String[] { abcd.TestUI.class.getName() });
}
}
My approach of solving it:
Download the latest version of java-simple-serial-connector(Which is the base library used for Processing's serial library), replace jssc.jar in the lib folder, and the error will be gone, and my application runs smoothly.
However the base library is 4 times bigger than the modified version used in Processing, so there may be some unnecessary features involved.
Seems like in their latest alpha version, Processing solved the same problem for exporting apps(at least in windows) by adding more look-up paths, while keeping their Serial library intact. I'm not familiar with their development environment, so I didn't look further into it. There may be a simpler solution.
I am starting to switch from a well-known Java build system to Gradle to build all my projects, and after barely two hours into it I have already been able to publish a new version of one of my projects without a problem -- a breeze.
But now I encounter a difficulty. In short, I need to replicate the functionality of this Maven plugin which generates the necessary files for a ServiceLoader-enabled service.
In short: given a base class foo.bar.MyClass, it generates a file named META-INF/services/foo.bar.MyClass whose content is a set of classes in the current project which implement that interface/extend that base class. Such a file would look like:
com.mycompany.MyClassImpl
org.othercompany.MyClassImpl
In order to do this, it uses I don't know what as a classloader, loads the Class objects for com.myCompany.MyClassImpl or whatever and checks whether this class implements the wanted interface.
I am trying to do the same in Gradle. Hours of googling led me to this plugin, but after discussing with its author a little, it appears this plugin is able to merge such files, not create them. So, I have to do that myself...
And I am a real beginner both with Gradle and Groovy, which does not help! Here is my current code, link to the full build.gradle here; output (which I managed to get somehow; doesn't work from a clean dir) shown below (and please bear with me... I do Java, and I am final happy; Groovy is totally new to me):
/*
* TEST CODE
*/
final int CLASS_SUFFIX = ".class".length();
final URLClassLoader classLoader = this.class.classLoader;
// Where the classes are: OK
final File classesDir = sourceSets.main.output.classesDir;
final String basePath = classesDir.getCanonicalPath();
// Add them to the classloader: OK
classLoader.addURL(classesDir.toURI().toURL())
// Recurse over each file
classesDir.eachFileRecurse {
// You "return" from a closure, you do not "continue"...
if (!isPotentialClass(it))
return;
// Transform into a class name
final String path = it.getAbsolutePath();
final String name = path.substring(basePath.length() + 1);
final String className = name.substring(0, name.length() - CLASS_SUFFIX)
.replace('/', '.');
// Try and load it
try {
classLoader.loadClass(className);
println(className);
} catch (NoClassDefFoundError ignored) {
println("failed to load " + className + ": " + ignored);
}
}
boolean isPotentialClass(final File file)
{
return file.isFile() && file.name.endsWith(".class")
}
The output:
com.github.fge.msgsimple.InternalBundle
failed to load com.github.fge.msgsimple.bundle.MessageBundle: java.lang.NoClassDefFoundError: com/github/fge/Frozen
failed to load com.github.fge.msgsimple.bundle.MessageBundleBuilder: java.lang.NoClassDefFoundError: com/github/fge/Thawed
com.github.fge.msgsimple.bundle.PropertiesBundle$1
com.github.fge.msgsimple.bundle.PropertiesBundle
com.github.fge.msgsimple.provider.MessageSourceProvider
com.github.fge.msgsimple.provider.LoadingMessageSourceProvider$1
com.github.fge.msgsimple.provider.LoadingMessageSourceProvider$2
com.github.fge.msgsimple.provider.LoadingMessageSourceProvider$3
com.github.fge.msgsimple.provider.LoadingMessageSourceProvider$Builder
com.github.fge.msgsimple.provider.LoadingMessageSourceProvider
com.github.fge.msgsimple.provider.MessageSourceLoader
com.github.fge.msgsimple.provider.StaticMessageSourceProvider$Builder
com.github.fge.msgsimple.provider.StaticMessageSourceProvider$1
com.github.fge.msgsimple.provider.StaticMessageSourceProvider
com.github.fge.msgsimple.source.MessageSource
com.github.fge.msgsimple.source.MapMessageSource$Builder
com.github.fge.msgsimple.source.MapMessageSource$1
com.github.fge.msgsimple.source.MapMessageSource
com.github.fge.msgsimple.source.PropertiesMessageSource
com.github.fge.msgsimple.locale.LocaleUtils
com.github.fge.msgsimple.serviceloader.MessageBundleFactory
com.github.fge.msgsimple.serviceloader.MessageBundleProvider
:compileJava UP-TO-DATE
The problem is in the two first lines: Frozen and Thawed are in a different project, which is in the compile classpath but not in the classpath I managed to grab so far... As such, these classes cannot even load.
How do I modify that code so as to have the full compile classpath availabe? Is my first question. Second question: how do I plug that code, when it works, into the build process?
Here are some hints:
Create a new URLClassLoader, rather than reusing an existing one.
Initialize the class loader with sourceSets.main.compileClasspath (which is an Iterable<File>) rather than classesDir.
Turn the code into a Gradle task class. For more information, see "Writing a simple task class" in the Gradle User Guide.
Ideally, you'd use a library like ASM to analyze the code, rather than using a class loader. To avoid the case where you cannot load a class because it internally references a class that's not on the compile class path, you may want to initialize the class loader with sourceSets.main.runtimeClasspath instead.
I am new to java and to the eclipse IDE.
I am running Eclipse
Eclipse SDK
Version: 3.7.1
Build id: M20110909-1335
On a windows Vista machine.
I am trying to learn from the book Thinking in Java vol4.
The author uses his own packages to reduce typing. However the author did not use Eclipse and this is where the problem commes in..
This is an example of the code in the book.
import java.util.*;
import static net.mindview.util.print.*;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello world");
print("this does not work");
}
this is the contents of print.Java
//: net/mindview/util/Print.java
// Print methods that can be used without
// qualifiers, using Java SE5 static imports:
package net.mindview.util;
import java.io.*;
public class Print {
// Print with a newline:
public static void print(Object obj) {
System.out.println(obj);
}
// Print a newline by itself:
public static void print() {
System.out.println();
}
// Print with no line break:
public static void printnb(Object obj) {
System.out.print(obj);
}
// The new Java SE5 printf() (from C):
public static PrintStream
printf(String format, Object... args) {
return System.out.printf(format, args);
}
} ///:~
The error I get the most is in the statement.
Import static net.mindview.util.print.*;
On this staement the Eclipse IDE says it cannot resolve net
also on the
print("this does not work");
The Eclipse IDE says that the class print() does not exist for the class HelloWorld.
I have been trying to get these to work, but with only limited success, The autor uses another 32 of these packages through the rest of the book.
I have tried to add the directory to the classpath, but that seems to only work if you are using the JDK compiler. I have tried to add them as libraries and i have tried importing them into a package in a source file in the project. I have tried a few other things but cant remember them all now.
I have been able to make one of the files work, the print.java file I gave the listing for in this message. I did that by creating a new source folder then making a new package in that foldeer then importing the print.java file into the package.
But the next time I try the same thing it does not work for me.
What I need is a way to have eclipse load all these .java files at start up so when I need them for the exercises in the book they will be there and work for me, or just an easy way to make them work everytime.
I know I am not the only one that has had this problem I have seen other questions about it on google searches and they were also asking about the Thinking In Java book.
I have searched this site and others and am just not having any luck.
Any help with this or sugestions are welcome and very appreciated.
thank you
Ok I have tried to get this working as you said, I have started a new project and I removed the static from the import statement, I then created a new source folder, then I created a new package in the source folder. Then I imported the file system and selected the the net.mindview.util folder.
Now the immport statement no longer gives me an error. But the the print statement does, the only way to make the print statement work is to use its fully qualified name. Here is the code.
import net.mindview.util.*;
public class Hello2 {
public static void main(String[] args) {
Hello2 test = new Hello2();
System.out.println();
print("this dooes not work");
net.mindview.util.Print.print("this stinks");
}
}
The Error on the print statement is:
The method print(String) is undefined for the type Hello2
and if I try to run it the error I get is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method print(String) is undefined for the type Hello2
at Hello2.main(Hello2.java:6)
The Statement::::: net.mindview.util.Print.print("this stinks") is the fully qualified print statement and it does not throw an error but it does totally defeat the purpose of the print.java file..
If you have any questions please ask Ill get back to you as soon as I can.
I've had similar issues. I solved it by following the steps below:
Click File->New->Java Project. Fill in UtilBuild for the ProjectName. Chose the option "Use project folder as root and click 'Finish'.
Right-click on UtilBuild in the PackageExplorer window and click New->package. For the Package Name, fill in net.mindview.util
Navigate within the unzipped Thinking In Java (TIJ) folder to TIJ->net\mindview\util. Here you will find all the source code (.java) files for util.
Select all the files in the net\mindview\util folder and drag them to the net.mindview.util package under UtilBuild in Eclipse. Chose the 'Copy Files' option and hit 'OK'.
You will probably already have the 'Build Automatically' option checked. If not, go to Project and click 'Build Automatically'. This will create the .class files from the .java source files.
In Eclipse, right-click on the project you were working on (the one where you couldn't get that blasted print() method to work!) Click Properties and Java Build Path->Libraries. Click 'Add Class Folder...' check the box for UtilBuild (the default location for the .class files).
I think the confusion here arises due to CLASSPATH. If you use Eclipse to build and run your code then Eclipse manages your CLASSPATH. (You don't have to manually edit CLASSPATH in the 'Environment Variables' part of your computer properties, and doing so changes nothing as far as Eclipse Build and Run are concerned.)
In order to call code that exists outside your current project (I will name this 'outside code' for convenience) you need to satisfy three things:
A. You need to have the .class files for that code (as .class files or inside a JAR)
B. You need to indicate in your source code where to look for the 'outside code'
C. You need to indicate where to start looking for the 'outside code'
In order to satisfy these requirements, in this example we:
A. Build the project UtilBuild which creates the .class files we need.
B. Add the statement import static net.mindview.util.Print.*; in our code
C. Add the Class Folder library in Eclipse (Java Build Path->Libraries).
You can investigate the effect of Step C by examining the .classpath file that lives directly in your project folder. If you open it in notepad you will see a line similar to the following:
<classpathentry kind="lib" path="/UtilBuild>
You should combine this with your import statement to understand where the compiler will look for the .class file. Combining path="/UtilBuild" and import static net.mindview.util.Print.*; tells us that the compiler will look for the class file in:
UtilBuild/net/mindview/util
and that it will take every class that we built from the Print.java file (Print.*).
NOTE:
There is no problem with the keyword static in the statement
import static net.mindview.util.Print.*;
static here just means that you don't have to give specify the class name from Print.java, just the methods that you want to call. If we omit the keyword static from the import statement, then we would need to qualify that print() method with the class it belongs to:
import net.mindview.util.Print.*;
//...
Print.print("Hello");
which is slightly more verbose than what is achieved with the static import.
OPINION:
I think most people new to Java will use Eclipse at least initially. The Thinking in Java book seems to assume you will do things via command line (hence it's guidance to edit environment variables in order to update CLASSPATH). This combined with using the util folder code from very early in the book I think is a source of confusion to new learners of the language. I would love to see all the source code organised into an Eclipse project and available for download. Short of that, it would be a nice touch to include the .class files in just the 'net/mindview/util' folder so that things would be a little easier.
U should import package static net.mindview.util not static net.mindview.util.Print
and you should extend the class Print to use its method.......
You should remove the static keyword from your import decleration, this: import static net.mindview.util.print.*; becomes this: import net.mindview.util.print.*;
If that also does not work, I am assuming you did the following:
Create your own project;
Start copying code directly from the book.
The problem seems to be that this: package net.mindview.util; must match your folder structure in your src folder. So, if your src folder you create a new package and name it net.mindview.util and in it you place your Print class, you should be able to get it working.
For future reference, you should always make sure that your package decleration, which is at the top of your Java class, matches the package in which it resides.
EDIT:
I have seen your edit, and the problem seems to have a simple solution. You declare a static method named print(). In java, static methods are accessed through the use of ClassName.methodName(). This: print("this dooes not work"); will not work because you do not have a method named print which takes a string argument in your Hello2 class. In java, when you write something of the sort methodName(arg1...), the JVM will look for methods with that signature (method name + parameters) in the class in which you are making the call and any other classes that your calling class might extend.
However, as you correctly noted, this will work net.mindview.util.Print.print("this stinks");. This is because you are accessing the static method in the proper way, meaning ClassName.methodName();.
So in short, to solve your problem, you need to either:
Create a method named print which takes a string argument in your Hello2 class;
Call your print method like so: Print.print("this stinks");
Either of these two solutions should work for you.
In my case I've dowloaded and decompressed the file TIJ4Example-master.zip. in eclipse workspace folder. The three packages : net.mindview.atunit, net.mindview.simple and net.mindview.util are in this point of the project :
and java programs runs with no problems (on the right an example of /TIJ4Example/src/exercises/E07_CoinFlipping.java)