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.
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");
}
}
I have two JPMS modules:
module-a
module-b
In module-a I have something like:
public class MyAppplication extends Application {
....
public static void addCss(String path) {
stage.getScene().getStylesheets().add(path);
}
}
In module-b I have CSS file which I want to add to MyApplication. How to do it in code in module-b? I can't understand how to pass path from another module.
I mean in module-b:
...
MyApplication.addCss(???);
...
EDIT
In OSGi I used the following solution in bundle-b (assuming, that module-a was bundle-a, and module-b was bundle-b):
String pathInBundleB = "com/foo/package-in-bundle-b/file.css"
Bundle bundleB = FrameworkUtil.getBundle(this.getClass()).getBundleContext().getBundle();
URL cssFileUrl = bundleB.getEntry(pathInBundleB);
MyApplication.addCss(cssFileUrl.toString());
I found the solution with the help of #AlanBateman.
Assuming, that css file is in com/foo/some-package/file.css I use the following code in module-b:
package com.foo.some-package;
public class SomeClass {
public void init() {
MyApplication.addCss(this.getClass().getResource("base.css").toString());
}
}
Besides, in module-info of module-b I have:
opens com.foo.some-package to module-a;
package org.apis.style.css;
public class CommonCss {
public static String getCommonCssStyle(){
return CommonCss.class.getClassLoader().getResource("common.css").toExternalForm();
}
}
Export this package to all.
In other module I add this
getStylesheets().add(CommonCss.getCommonCssStyle());
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 am creating a little game with libgdx framework and netbeans 8. I have all java classes in a single package that match with the directory structure.
The problem is that i cant import or isntantiate classes, for example:
package com.myfolder.folder2;
import ...
public class myclass1{
private myclass2 mc2;
etc...
}
In this case myclass2 is public and is inside the package but netbeans complains "cannot find symbol".
If i try with alt+enter, netbeans says "Create class myclass2 in package com.myfolder.folder2" or the same like an inner class. If i press the first option, netbeans create a class in the package with the file name myclass2_1 (becouse myclass2 exists!), and myclass1 doesnt recognize the new class.
If i try to import the class:
import com.myfolder.folder2.myclass2;
It gives me the same error, and in fact the code completion tool only gives me one crazy option in the import sentence:
import com.myfolder.folder2.myclass1;
Import the same class.
What can i do? I never have these problems using netbeans.
PD: Sorry for my english :)
You can use a class inside the same package like this:
ClassName classVariableName = new ClassName();
Then when you want to run something from the class you would put
classVariableName.MethodThatIWantToRun();
Or if you want to access a property from that method you would access it in a very similar way:
classVarabileName.PropertyIWantToAccess
Example:
You have one class with a property you want to access:
class MyClass {
public int MyProperty = 5;
}
You access it in this class:
public class MainClass {
public static void main(String[] args) {
MyClass myClass = new MyClass();
System.out.println(myClass.MyProperty);
}
}
If that doesn't work than you might have some other problem.
It was an error with one of my class package definition:
public class DesktopLauncher{
public static void main(String... args){
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
.
.
.
new LwjglApplication(new MyClass, config);
}
}
It was in MyClass, becouse i copied a snippet from an older project, and accidentally copied the older package.
NetBeans is not smart enough,
Solution: just declare the package name in all classes, example:
Class A:
package test;
public class ClassA {
public static void main(String[ ] args) {
ClassB.myFunctionB();
}
}
Class B:
package test;
public class ClassB {
public static void myFunctionB () {
System.out.print("I am ClassB!");
}
}
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.