I want to write a classLoader that can help me implement customized classes and ultimately a whole component at run time. Right now I'm in process of loading the class.
I'm trying to load this role.java file. However when I get to this part of the code:
myClass = super.defineClass(className, classData, 0, classData.length);
I get this exception:
Exception in thread "main" java.lang.ClassFormatError: Incompatible magic value 1885430635 in class file C:\Users\ARIFAH\Downloads\Compressed\eUML2 free version\with classLoader code\2\archetypedComponentWithNull\src\aC\Role/java
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at customCL.customClassLoader.loadClass(customClassLoader.java:116)
at java.lang.ClassLoader.loadClass(Unknown Source)
at customCL.customClassLoader.main(customClassLoader.java:145)
I've read posts saying "you need something like OSGi". That would be similar to working on something new from scratch, which I'd like to avoid.
Why am I getting this error?
You aren't actually loading a real class file. The magic value of any valid class file is 0xCAFEBABE, and this magic in hex is 0x7061636B.
Notice that if we convert 0x7061636B to ASCII byte by byte, it turns out to be the string "pack". This means that the file you think is a class file actually starts with the string "pack".
Related
Referring to : http://jboss-javassist.github.io/javassist/tutorial/tutorial2.html
method.insertBefore("{ System.out.println($1);}");
This statement gives me following error:
Exception: javassist.CannotCompileException: [source error] no such field: $1
javassist.CannotCompileException: [source error] no such field: $1
at javassist.CtBehavior.insertBefore(CtBehavior.java:774)
at javassist.CtBehavior.insertBefore(CtBehavior.java:734)
at com.here.debugHelper.DurationTransformer.transform(DurationTransformer.java:124)
at sun.instrument.TransformerManager.transform(Unknown Source)
at sun.instrument.InstrumentationImpl.transform(Unknown Source)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at com.here.debugHelper.TestInstrumentation.main(TestInstrumentation.java:10)
Caused by: compile error: no such field: $1
at javassist.compiler.TypeChecker.fieldAccess(TypeChecker.java:845)
at javassist.compiler.TypeChecker.atFieldRead(TypeChecker.java:803)
at javassist.compiler.TypeChecker.atMember(TypeChecker.java:988)
at javassist.compiler.JvstTypeChecker.atMember(JvstTypeChecker.java:66)
at javassist.compiler.ast.Member.accept(Member.java:39)
at javassist.compiler.JvstTypeChecker.atMethodArgs(JvstTypeChecker.java:221)
at javassist.compiler.TypeChecker.atMethodCallCore(TypeChecker.java:735)
at javassist.compiler.TypeChecker.atCallExpr(TypeChecker.java:695)
at javassist.compiler.JvstTypeChecker.atCallExpr(JvstTypeChecker.java:157)
at javassist.compiler.ast.CallExpr.accept(CallExpr.java:46)
at javassist.compiler.CodeGen.doTypeCheck(CodeGen.java:242)
at javassist.compiler.CodeGen.atStmnt(CodeGen.java:330)
at javassist.compiler.ast.Stmnt.accept(Stmnt.java:50)
at javassist.compiler.CodeGen.atStmnt(CodeGen.java:351)
at javassist.compiler.ast.Stmnt.accept(Stmnt.java:50)
at javassist.compiler.Javac.compileStmnt(Javac.java:567)
at javassist.CtBehavior.insertBefore(CtBehavior.java:754)
... 17 more
Moreover,the same error appears when I use any parameter(passed to the parameter) or any local variable instead of '$1'. This has been covered in this question, but I don't really understand the solution there.
There is this other post with same question but no answer.
Please help. Thank you
Alright, this is how I worked around the problem. There were few mistakes that I was overlooking and some things that I learnt. I am sharing this since I could not find the content directly addressing the issue anywhere.
Referring to this answer and this article:
The insertBefore, insertAfter and other such methods cannot access any local variable but can access method parameter of the method by their names. no such field error occurs if attempt is made to access local variable.
These methods cannot access any parameter declared within them as a process of instrumentation.
ctmethod.insertBefore("{int i = 4; int j = 9;}")
ctmethod.insertBefore("i = 5;");
ctMethod.insertAfter("j = 9;");
The above code will give no such field: j(and i) error
insertBefore, insertAfter, expect a single statement, or a single block of code as done in first line of above code snippet.
This error no such field appears in case when variables are used in ctmethod.addcatch() too.
ctmethod.addLocalVariable() helps in declaring a variable that can be accessed by insertBefore(), etc. However, .addCatch() will still give no such field error if you try to use variable declared using .addLocalVariable()
I was getting no such field: $1 due to my silly mistake. I was going iterating through a number of method in a class, so the error was due to the fact that some of those methods had zero arguments. $1,$2.. and $args work well as explained in this doc.
P.S. I will add further tips as I come across them and any corrections are welcomed.
Can any body suggest me which jar i shld use to resolve the below exception,
Exception in thread "main" java.lang.NoSuchMethodError: org.neo4j.graphdb.factory.GraphDatabaseSetting$BooleanSetting.<init>(Ljava/lang/String;)V
at org.neo4j.shell.ShellSettings.<clinit>(ShellSettings.java:37)
at sun.misc.Unsafe.ensureClassInitialized(Native Method)
at sun.reflect.UnsafeFieldAccessorFactory.newFieldAccessor(Unknown Source)
at sun.reflect.ReflectionFactory.newFieldAccessor(Unknown Source)
at java.lang.reflect.Field.acquireFieldAccessor(Unknown Source)
at java.lang.reflect.Field.getFieldAccessor(Unknown Source)
at java.lang.reflect.Field.get(Unknown Source)
at org.neo4j.kernel.configuration.AnnotatedFieldHarvester.findStatic(AnnotatedFieldHarvester.java:47)
at org.neo4j.kernel.configuration.AnnotationBasedConfigurationMigrator.<init>(AnnotationBasedConfigurationMigrator.java:40)
at org.neo4j.kernel.configuration.Config.<init>(Config.java:89)
at org.neo4j.kernel.InternalAbstractGraphDatabase.<init>(InternalAbstractGraphDatabase.java:218)
at org.neo4j.kernel.EmbeddedGraphDatabase.<init>(EmbeddedGraphDatabase.java:103)
at org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:88)
at org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:207)
at org.neo4j.graphdb.factory.GraphDatabaseFactory.newEmbeddedDatabase(GraphDatabaseFactory.java:69)
at com.Neo4J.src.EmbeddedNeo4j.createDb(EmbeddedNeo4j.java:48)
at com.Neo4J.src.EmbeddedNeo4j.main(EmbeddedNeo4j.java:38).
I have already included the below jar,
neo4j-kernel-1.9.3.jar.
Thanks.
Make sure you have the matching neo4j-shell jar file.
The command javap -v -classpath neo4j-shell-1.9.3.jar org.neo4j.shell.ShellSettings | grep invoke indicates to me that there are only five methods called by ShellSettings. One is the Object default constructor, but that's during the constructor for ShellSettings, not the static class initialization <clinit>. The others are all from class org.neo4j.helpers.Settings. setting is called four times, in two different overloaded versions, matches and illegalValueMessage each once.
So in the 1.9.3 version of neo4j, the call to the constructor of GraphDatabaseSetting$BooleanSetting which is mentioned in your stack trace does not occur. therefore your ShellSettings class must come from some other version which is not binary compatible to 1.9.3. Use compatible versions, and you should be fine.
I am using the Apertium Translator and using the sample code they provide. My code is like this.
import com.robtheis.aptr.language.Language;
import com.robtheis.aptr.translate.Translate;
public class Test {
public static void main(String[] args) throws Exception {
// Set the Apertium API Key - Get yours at http://api.apertium.org/register.jsp
Translate.setKey("BNSCFhEL8DoTApc2I1+aa3UYkVg");
String translatedText = Translate.execute("Hola, mundo!", Language.SPANISH, Language.ENGLISH);
System.out.println(translatedText);
}
}
I have no errors or warnings and when I run the program I get the following errors.
Exception in thread "main" java.lang.NoClassDefFoundError: org/json/simple/JSONValue
at com.robtheis.aptr.ApertiumTranslatorAPI.jsonSubObjToString(ApertiumTranslatorAPI.java:195)
at com.robtheis.aptr.ApertiumTranslatorAPI.retrieveSubObjString(ApertiumTranslatorAPI.java:140)
at com.robtheis.aptr.translate.Translate.execute(Translate.java:56)
at maple.Test.main(Test.java:11)
Caused by: java.lang.ClassNotFoundException: org.json.simple.JSONValue
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 4 more
The .jar I'm using is the second one from https://github.com/rmtheis/apertium-translator-java-api/downloads
You have to download the first one. The first jar file (apertium-translator-java-api-0.2-jar-with-dependencies.jar) contains the all dependencies needed..
Or you add a json library to your project path..
Well JVM is not able to find some class at Runtime which was available at compile time. That is the reason of NoClassDefFoundError
Below you also have ClassNotFoundException for this class org.json.simple.JSONValue
which means you are trying to load the particular class at run-time by name.
Both of them related to Java Class Path.
I don't know alot about jSON stuff. But you are missing this file org.json.simple.JSONValue you can take it from here http://code.google.com/p/json-simple/
add the above jar file in your class path . And the code will definitely run. Guaranteed.!!!
Thanks
I wanted to instrument some methods/classes in Java. For that purpose I wrote an Java agent that instruments only a few classes that I choose.
I use the following code to get the loaded classes and filter some of them:
instrumentation.addTransformer(myTransformer,true);
Class[] loadedClasses=instrumentation.getAllLoadedClasses();
Class[] modifiableClasses=ModifiableClasses(loadedClasses,instrumentation);
Class[] filteredClasses=filterClasses(modifiableClasses);
if(instrumentation.isRetransformClassesSupported()){
System.out.println("retransformation is Supported");
instrumentation.retransformClasses(filteredClasses);
}
this should not create any problem filterClasses returns some classes that I want to be instrumented normally I want to instrument these Classes:
Ljava/nio/Buffer;
Ljava/util/HashMap$Entry;
Ljava/nio/HeapCharBuffer;
Ljava/nio/CharBuffer;
Ljava/lang/ClassLoader;
Ljava/lang/Class;
Ljava/util/HashMap;
Ljava/nio/ByteBuffer;
Ljava/lang/System;
Ljava/io/BufferedWriter;
Ljava/lang/String;
Ljava/io/OutputStreamWriter;
Ljava/io/BufferedOutputStream;
Ljava/nio/charset/CoderResult;
Ljava/io/Writer;
Ljava/util/HashSet;
Ljava/nio/charset/CharsetEncoder;
Ljava/io/FileOutputStream;
Ljava/io/PrintStream;
everything works fine I print the instrumented and unistrumented classes in specific folders for debug. I use the asm CoreAPI to add some instructions at the beginning and the end of methods I dont instrument Constructors,native methods, abstract methods and static variables. When I just instrument the new classes that are being loaded everything works fine. I guess I dont understand something with the ClassLoader or something specific here is what I get on the Console:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(Unknown Source)
at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(Unknown Source)
Caused by: java.lang.InternalError
at sun.instrument.InstrumentationImpl.retransformClasses0(Native Method)
at sun.instrument.InstrumentationImpl.retransformClasses(Unknown Source)
at my.Agent.Watcher.premain(Watcher.java:88)
... 6 more
FATAL ERROR in native method: processing of -javaagent failed
I am thankful for any help I can get even a link or a hint in the right direction.
Sorry guys my mistake after looking more precisely in the instrumented classes I found Errors which I will have to solve, if I want this to work. An admin/mod can close this thread .
I have 2 java program located seperately
One in c:\test and the other in c:\test\new
I can compile both of it without any error \javac
But when i try to execute the file \java
it shows the error like this
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at ButtonFrame.makeButton(ButtonTest3.java:42)
at ButtonFrame.<init>(ButtonTest3.java:29)
at ButtonTest$1.run(ButtonTest.java:17)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
i put this in my classpath
CLASSPATH value- C:\test;C:\test\new
but if i change the order of the value in CLASSPATH to this
CLASSPATH value- C:\test\new;C:\test
the error is simply gone
Why?? this could happening
Only the order matters?
You've a class with the same name in the both folders. In C:\test there's a version of the ButtonTest3 class which contains a programming bug causing this NullPointerException. In C:\test\new there's a different version of the ButtonTest3 class which doesn't contain this bug, or probably there's a ButtonTest class which does entirely different things than the one in C:\test.
Cleanup your classpath. It's not good to have duplicate different versioned classes with the same signature in the classpath. If your intent is that new is supposed to be a package identifier, then you need to leave it away from the classpath. However, such a package name would have resulted in a compilation error, so that can't be it.
As to the bug, a NullPointerException is relatively trivial to naildown and fix. First look at the first line of the stacktrace:
at ButtonFrame.makeButton(ButtonTest3.java:42)
It's telling that it has occurred in line 42 of ButtonTest3 class, inside the makeButton() method. Now go to line 42 of ButtonTest3.java, it'll look something like:
someObject.doSomething();
Look there where a dot operator . is been used to invoke a method or access a field of some object. The NullPointerException means that someObject is null at the particular moment. There is no instance!
It's an easy fix: just ensure that it is not null at the moment you're invoking/accessing it:
someObject = new SomeObject();
// ...
someObject.doSomething();
Well, I don't believe you can have two classes defined in a single source file. You can have them defined as a subclass.
According to the Java spec:
Each class file contains the
definition of a single class or
interface. Although a class or
interface need not have an external
representation literally contained in
a file (for instance, because the
class is generated by a class loader),
we will colloquially refer to any
valid representation of a class or
interface as being in the class file
format.format.
You could place ButtonFrame inside ButtonTest2.
public class ButtonTest2
{
public static void main(String[] args)
{
...
ButtonFrame frame = new ButtonFrame();
}
class ButtonFrame extends JFrame {
....
}
}
Or, put them in different java files.
You have two classes at top level in program, thats wrong. But keeping that aside, your program is not getting compiled at first place.
To successfully compile the program use the following NppExec script:
cmd /c cd "$(CURRENT_DIRECTORY)" && "%JAVA_HOME%\bin\javac" "$(FULL_CURRENT_PATH)"
cmd /k cd "$(CURRENT_DIRECTORY)" && "%JAVA_HOME%\bin\java" "$(NAME_PART)" && exit
Make sure that you have your JDK folder set to JAVA_HOME environment variable.
and try again.