I got a java class from which I created a jar file to access the class in another project.
the class looks like this
public class RunMain {
private ArgumentObject argObject = null;
private String outputFile = null;
private SimObject simObject = null;
public RunMain() {
}
public RunMain(String file) {
outputFile = file;
}
public static void main(String[] args) throws Exception {
new RunMain().doMain(args);
}
public void testMethod(){
}
public void blaMethod(){
}
public SimObject getResults(){
return simObject;
}
public void doMain(String[] args) throws Exception {
// do some stuff
}
// write term and doc vectors to bin files
void writeVectorStore() throws Exception{
// do some stuff
}
}
My problem is, that when I now wanna access the methods in another project I can only call the main method or the doMain method.
RunMain run = new RunMain();
run.doMain(arguments);
this works fine
SimObject simObject = run.getResults();
this is marked red with "The method getResults() is undefined for the type RunMain"
Does someone have an idea why this is happening?
I have two ideas:
The jar file contains an earlier version of the compiled class.
You use an earlier version of the jar file.
But it is not possible that only some public methods of a class are accessible a jar file.
A couple things to check...
Make sure the project using this jar file doesn't have its own version of class RunMain on the classpath. It will "override" RunMain in the jar file. If there is a local version of the class thant doesn't have the method getResults(), well there's your compiler error.
If you've been working on the .jar file for awhile.. better re-build it to make sure the code in there is the latest version. It's possible you created the jar, then added a method, but didn't recreate the jar file. Then make sure the new jar file is being referenced by your project.
Related
I'm trying to edit the memory of another program. I'm trying to use IntelliJ idea to do it. So I've added the Java-Memory-Manipulation library and it's dependencies as Libraries in the IntelliJ project. And it compiles. and gives me a jar with all of the library files contained inside it. But when I try to run it it fails with NoClassDefFoundError on a class from JavaMemoryManipulation. Here is my code. Any help would be appreciated.
Note these are seperate class files.
public class Main {
public static void main(String[] args) {
processLoader processLoader = new processLoader();
System.out.println(processLoader.csgo.toString());
}
}
public final class processLoader {
Process csgo;
{
csgo = Processes.byName("csgo_linux64");
}
}
Recently I'm creating something that have to load/unload external jar packages dynamically. I'm now trying to do this with URLClassLoader, but I keep getting NoClassDefFoundError while trying to make new instances.
It seems that the external class is loaded successfully since the codes in the constructor are executed, but ClassNotFoundException and NoClassDefFoundError still keep being thrown.
I made an small package that recreates the error and here are the codes:
The codes below are in ExternalObject.class ,which is put in a .jar file, that I'm trying to load dynamically:
package test.outside;
import test.inside.InternalObject;
public class ExternalObject
{
private final String str;
public ExternalObject()
{
this.str = "Creating an ExternalObject with nothing.";
this.print();
}
public ExternalObject(InternalObject inObj)
{
this.str = inObj.getString();
this.print();
}
public void print()
{
System.out.println(this.str);
}
}
And the codes below are in InternalObject.class:
package test.inside;
public class InternalObject
{
private final String str;
public InternalObject(String s)
{
this.str = s;
}
public String getString()
{
return this.str;
}
}
I tested the file with Main.class below:
package test.inside;
import java.io.File;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
import test.outside.ExternalObject;
public class Main
{
public static void main(String[] args)
{
try
{
File externalJar = new File("F:\\Dev\\ext.jar");
URLClassLoader uclTest = new URLClassLoader(new URL[]{externalJar.toURI().toURL()});
Class<?> clazz = uclTest.loadClass("test.outside.ExternalObject");
InternalObject inObj = new InternalObject("Creating an ExternalObject with an InternalObject.");
try
{
System.out.println("Test 1: Attempt to create an instance of the ExternalObject.class with an InternalObject in the constructor.");
Constructor<?> conTest = clazz.getConstructor(InternalObject.class);
ExternalObject extObj = (ExternalObject)conTest.newInstance(inObj);
}
catch(Throwable t)
{
System.out.println("Test 1 has failed. :(");
t.printStackTrace();
}
System.out.println();
try
{
System.out.println("Test 2: Attempt to create an instance of the ExternalObject.class with a void constructor.");
Constructor<?> conTest = clazz.getConstructor();
ExternalObject extObj = (ExternalObject)conTest.newInstance();
}
catch(Throwable t)
{
System.out.println("Test 2 has failed. :(");
t.printStackTrace();
}
uclTest.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Both InternalObject.class and Main.class are in a jar pack which is included in the classpath while launched.
And I got this in the console:
Console output screenshot
As the codes this.print() in both constructors of ExternalObject.class are executed, I have really no idea what's wrong. Help! :(
UPDATE: Thank you wero!!! But I actually want to make an instance of ExternalObject for further usage such as accessing methods in it from other classes. Is there any way that I can return the created instance as an ExternalObject? Or I have to use getMethod() and invoke() to access the methods?
Sincerely,
Zevin
Your Main class references ExternalObject and therefore the compiled Main.class has a dependency on ExternalObject.
Now when you run Main and ExternalObject is only available in ext.jar but not in the classpath used to run Main the following happens:
The uclTest classloader successfully loads ExternalObject from ext.jar. Also creation succeeds (seen by the print statement in the constructor).
But what fails are the assignments to local variables ExternalObject extObj.
Main cannot use the loaded class ExternalObject since it is loaded by a different classloader. There is also no ExternalObject in the classpath of Main and you get a NoClassDefFoundError.
Your test should run without problems when you remove the two assignments ExternalObject extObj = (ExternalObject).
I think because there are two classLoaders involved, and you try to cast an object from a classLoader to an object from another class loader. But is just a guess.
How you are running the Main class is causing the problem.
As you said, I have created jar called ext1.jar with ExternalObject and InternalObjct class files inside it.
And created ext.jar with Main and InternalObject class files.
If I run the following command, it throws Exception as you mentioned
java -classpath .;C:
\path\to\ext.jar test.inside.Main
But, If I run the following command, it runs fine without any Exception
java -classpath .;C:
\path\to\ext1.jar;C:
\path\to\ext.jar test.inside.Main
Hooray!! I just found a better way for my codes! What I did is creating an abstract class ExternalBase.class with all abstract methods I need, then inherit ExternalObject.class from ExternalBase.class. Therefore dynamically loaded class have to be neither loaded into the custom loader nor imported by the classes that use the object, and the codes work totally perfect for me. :)
I have a jar file which consisting of multiple class files.
Main class file's java file is like
class Main
{
public void setUserType()
{
String utype="user";
}
}
now i want to update the Main class file with usertype "user" to "admin" and recreate the jar file
can you suggest me how can i do this so that the new jar file should have usertype "admin"
These changes should be done through programming not through editor like netbeans or eclipse
Instead of hardcoding things, you should define your code to accept properties either via property file or via environment/System property or command line argument when you start your application like below:
class Main {
public void setUserType(String value) {
String utype=value;//or use System.getProperty("value");if you used -Dvalue=admin in command line for example.
}
public static void main(String args[]) {//see main accepts command line argument
if (args.length == 0) {
throw new IllegalArgumentException("Required parameters are missing");
}
Main main = new Main();
main(args[0]);//just pass whatever you pass as system parameter when you start your application
//if you dont want to pass string across multiple methods and classes just use System.setProperty("value", args[0]); and use it like System.getProperty("value") to access it from anywhere without actually passing this string across.
}
}
And run it with user/admin as you like:
java Main admin
java Main user
i am running following code in My Eclipse...
package foo;
public class Test
{
public static void main(String[] args)
{
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("foo/Test.class"));
}
}
But iam getting o/p as null on console.
Help me..
Use following code to also find out where the classloader is going to find the resource. The following code worked for me in a blank project.
public class Test {
public static void main(String[] args)
{
URLClassLoader loader = (URLClassLoader) Test.class.getClassLoader();
System.out.println(Arrays.toString(loader.getURLs()));
System.out.println(loader.getResource("foo/Test.class"));
}
}
Make sure that there are no errors in workspace.
See if the file exists in the Navigator view.
Try cleaning the project once.
I was trying to model my project based on this project at Github.
public class DroolsPlannerPoCApp {
....
private static final String SOLVER_CONFIG = "/ServiceDeliverySolverConfig.xml";
....
private Solver createSolver() {
XmlSolverConfigurer configurer = new XmlSolverConfigurer();
configurer.configure( SOLVER_CONFIG );
return configurer.buildSolver();
}
The file mentioned in SOLVER_CONFIG lies in the resources directory (see here).
I tried to do the same thing.
package in.co.technovia.sudoku;
import java.util.ArrayList;
....
public class App{
private static final String SOLVER_CONFIG = "/solver.xml";
public static void main(String[] args){
SudokuGenerator sg = new SudokuGenerator();
....
}
private static Solver createSolver(){
XmlSolverConfigurer configurer = new XmlSolverConfigurer();
configurer.configure(SOLVER_CONFIG);
return configurer.buildSolver();
}
}
And there was fail.
jesvin#Jesvin-Technovia:~/dev/drools/sudoku$ java in.co.technovia.sudoku.AppException in thread "main" java.lang.IllegalArgumentException: The solver configuration (/solver.xml) does not exist.
at org.drools.planner.config.XmlSolverConfigurer.configure(XmlSolverConfigurer.java:79)
at in.co.technovia.sudoku.App.createSolver(App.java:67)
at in.co.technovia.sudoku.App.main(App.java:43)
I understand that main/resources mean something for Maven builds. But I am building my project manually.
Question: How do I implement the same thing (from resources) in my own project? Where must I place the file and what must I specify in the SOLVER_CONFIG?
The function itself is implemented as:
public XmlSolverConfigurer configure(String resource) {
return configure(getClass().getResourceAsStream(resource));
}
Put the resources on the classpath, for example, in the source directory.
All Maven does is merge the src/main/resources package/directory tree into the target classpath, maintaining the same package/folder layout.
If you build manually you need to copy the resources manually into the classpath, i.e. copy the XML file in the root path of your generated classes directory.