GWT-Jackson-Apt seemingly undefined class constructor call - java

Looking at trying to use the GWT-Jackson-Apt library for doing certain RPC, but when looking at examples and trying to run some demos there are always interfaces with a bizarre undefined constructor call.
#JSONMapper
public interface SampleMapper extends ObjectMapper<SimpleBean> {
SampleMapper INSTANCE = new App_SampleMapperImpl();
}
source: https://github.com/DominoKit/gwt-jackson-apt/blob/f60d0358b90bcbf78d066796f680aeae1d7156bb/samples/basic/basic-client/src/main/java/org/dominokit/jacksonapt/samples/basic/App.java
I've been digging around, but there is no definition of App_SampleMapperImpl() anywhere in the source code. And it doesn't compile, saying that there is an undefined symbol
The exact same thing is done in the readme file's exmaples which can be found on this page: https://github.com/DominoKit/gwt-jackson-apt/tree/f60d0358b90bcbf78d066796f680aeae1d7156bb
can anyone explain what is going on here? How is this constructor being defined, or implied? And what do I need to do to make the example compile?

Assuming you are making a Maven project, the important thing is to include the annotation processor which generates the mappers. Then, once the project knows how to generate them, you'll be able to use them in your code.
Annotation Processors run while the compiler is running, which means you technically get to write code which doesn't appear it will compile. Then, as the compiler is running, it asks all registered annotation processors to please generate code based on the annotations and existing types (not the missing references like App_Sample_MapperImpl as you might think). The processor then runs, generates the missing class, and then the compile continues.
Usually what happens is that you build while writing code (eclipse, for example, does this every time a file is saved, intellij does it when you ask for a build, etc), and then the class exists and can be referenced going forward. Even when the project is cleaned and rebuilt, while the reference seems like it should not work, it will work as soon as the compiler runs.
In this case, we'll need to follow the example to make sure the processor is present. in https://github.com/DominoKit/gwt-jackson-apt/blob/f60d0358b90bcbf78d066796f680aeae1d7156bb/samples/shared-mappers/shared-mappers-shared/pom.xml, we see this in the dependencies:
<dependency>
<groupId>org.dominokit.jackson</groupId>
<artifactId>jackson-apt-processor</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
This is marked scope=provided since it is only needed to compile, then shouldn't be included in later dependency graphs. For each specific IDE, you may need to specify additional options to get it to re-run automatically (a checkbox in Eclipse, nothing in IntelliJ I believe, and I haven't used other IDEs in too long to say).
One final note for maven: you must use a relatively recent maven-compiler-plugin so that generated code is handled correctly: latest is 3.8.0, published July 2018, but I think anything after 3.5.1 will be sufficient if you must use an older one.

Just follow the example on the main page of the project: https://github.com/DominoKit/gwt-jackson-apt/
Does that work ?

Related

To replace object property value from Ontology [duplicate]

I'm getting a NoSuchMethodError error when running my Java program. What's wrong and how do I fix it?
Without any more information it is difficult to pinpoint the problem, but the root cause is that you most likely have compiled a class against a different version of the class that is missing a method, than the one you are using when running it.
Look at the stack trace ... If the exception appears when calling a method on an object in a library, you are most likely using separate versions of the library when compiling and running. Make sure you have the right version both places.
If the exception appears when calling a method on objects instantiated by classes you made, then your build process seems to be faulty. Make sure the class files that you are actually running are updated when you compile.
I was having your problem, and this is how I fixed it. The following steps are a working way to add a library. I had done the first two steps right, but I hadn't done the last one by dragging the ".jar" file direct from the file system into the "lib" folder on my eclipse project. Additionally, I had to remove the previous version of the library from both the build path and the "lib" folder.
Step 1 - Add .jar to build path
Step 2 - Associate sources and javadocs (optional)
Step 3 - Actually drag .jar file into "lib" folder (not optional)
Note that in the case of reflection, you get an NoSuchMethodException, while with non-reflective code, you get NoSuchMethodError. I tend to go looking in very different places when confronted with one versus the other.
If you have access to change the JVM parameters, adding verbose output should allow you to see what classes are being loaded from which JAR files.
java -verbose:class <other args>
When your program is run, the JVM should dump to standard out information such as:
...
[Loaded junit.framework.Assert from file:/C:/Program%20Files/junit3.8.2/junit.jar]
...
If using Maven or another framework, and you get this error almost randomly, try a clean install like...
clean install
This is especially likely to work if you wrote the object and you know it has the method.
This is usually caused when using a build system like Apache Ant that only compiles java files when the java file is newer than the class file. If a method signature changes and classes were using the old version things may not be compiled correctly. The usual fix is to do a full rebuild (usually "ant clean" then "ant").
Sometimes this can also be caused when compiling against one version of a library but running against a different version.
I had the same error:
Exception in thread "main" java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonGenerator.writeStartObject(Ljava/lang/Object;)V
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:151)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292)
at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3681)
at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3057)
To solve it I checked, firstly, Module Dependency Diagram (click in your POM the combination -> Ctrl+Alt+Shift+U or right click in your POM -> Maven -> Show dependencies) to understand where exactly was the conflict between libraries (Intelij IDEA). In my particular case, I had different versions of Jackson dependencies.
1) So, I added directly in my POM of the project explicitly the highest version - 2.8.7 of these two.
In properties:
<jackson.version>2.8.7</jackson.version>
And as dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
2) But also it can be solved using Dependency Exclusions.
By the same principle as below in example:
<dependency>
<groupId>group-a</groupId>
<artifactId>artifact-a</artifactId>
<version>1.0</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
Dependency with unwanted version will be excluded from your project.
This can also be the result of using reflection. If you have code that reflects on a class and extracts a method by name (eg: with Class.getDeclaredMethod("someMethodName", .....)) then any time that method name changes, such as during a refactor, you will need to remember to update the parameters to the reflection method to match the new method signature, or the getDeclaredMethod call will throw a NoSuchMethodException.
If this is the reason, then the stack trace should show the point that the reflection method is invoked, and you'll just need to update the parameters to match the actual method signature.
In my experience, this comes up occasionally when unit testing private methods/fields, and using a TestUtilities class to extract fields for test verification. (Generally with legacy code that wasn't designed with unit testing in mind.)
If you are writing a webapp, ensure that you don't have conflicting versions of a jar in your container's global library directory and also in your app. You may not necessarily know which jar is being used by the classloader.
e.g.
tomcat/common/lib
mywebapp/WEB-INF/lib
For me it happened because I changed argument type in function, from Object a, to String a. I could resolve it with clean and build again
In my case I had a multi module project and scenario was like com.xyz.TestClass was in module A and as well as in module B and module A was dependent on module B. So while creating a assembly jar I think only one version of class was retained if that doesn't have the invoked method then I was getting NoSuchMethodError runtime exception, but compilation was fine.
Related : https://reflectoring.io/nosuchmethod/
Why anybody doesn't mention dependency conflicts? This common problem can be related to included dependency jars with different versions.
Detailed explanation and solution: https://dzone.com/articles/solving-dependency-conflicts-in-maven
Short answer;
Add this maven dependency;
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<rules>
<dependencyConvergence />
</rules>
</configuration>
</plugin>
Then run this command;
mvn enforcer:enforce
Maybe this is the cause your the issue you faced.
It means the respective method is not present in the class:
If you are using jar then decompile and check if the respective version of jar have proper class.
Check if you have compiled proper class from your source.
I have just solved this error by restarting my Eclipse and run the applcation.
The reason for my case may because I replace my source files without closing my project or Eclipse.
Which caused different version of classes I was using.
Try this way: remove all .class files under your project directories (and, of course, all subdirectories). Rebuild.
Sometimes mvn clean (if you are using maven) does not clean .class files manually created by javac. And those old files contain old signatures, leading to NoSuchMethodError.
Just adding to existing answers. I was facing this issue with tomcat in eclipse. I had changed one class and did following steps,
Cleaned and built the project in eclpise
mvn clean install
Restarted tomcat
Still I was facing same error. Then I cleaned tomcat, cleaned tomcat working directory and restarted server and my issue is gone. Hope this helps someone
These problems are caused by the use of the same object at the same two classes.
Objects used does not contain new method has been added that the new object class contains.
ex:
filenotnull=/DayMoreConfig.conf
16-07-2015 05:02:10:ussdgw-1: Open TCP/IP connection to SMSC: 10.149.96.66 at 2775
16-07-2015 05:02:10:ussdgw-1: Bind request: (bindreq: (pdu: 0 9 0 [1]) 900 900 GEN 52 (addrrang: 0 0 2000) )
Exception in thread "main" java.lang.NoSuchMethodError: gateway.smpp.PDUEventListener.<init>(Lgateway/smpp/USSDClient;)V
at gateway.smpp.USSDClient.bind(USSDClient.java:139)
at gateway.USSDGW.initSmppConnection(USSDGW.java:274)
at gateway.USSDGW.<init>(USSDGW.java:184)
at com.vinaphone.app.ttn.USSDDayMore.main(USSDDayMore.java:40)
-bash-3.00$
These problems are caused by the concomitant 02 similar class (1 in src, 1 in jar file here is gateway.jar)
To answer the original question. According to java docs here:
"NoSuchMethodError" Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
If it happens in the run time, check the class containing the method is in class path.
Check if you have added new version of JAR and the method is compatible.
I fixed this problem in Eclipse by renaming a Junit test file.
In my Eclipse work space I have an App project and a Test project.
The Test project has the App project as a required project on the build path.
Started getting the NoSuchMethodError.
Then I realized the class in the Test project had the same name as the class in the App project.
App/
src/
com.example/
Projection.java
Test/
src/
com.example/
Projection.java
After renaming the Test to the correct name "ProjectionTest.java" the exception went away.
NoSuchMethodError : I have spend couple of hours fixing this issue, finally fixed it by just renaming package name , clean and build ... Try clean build first if it doesn't works try renaming the class name or package name and clean build...it should be fixed. Good luck.
I ran into a similar problem when I was changing method signatures in my application.
Cleaning and rebuilding my project resolved the "NoSuchMethodError".
Above answer explains very well ..just to add one thing
If you are using using eclipse use ctrl+shift+T and enter package structure of class (e.g. : gateway.smpp.PDUEventListener ), you will find all jars/projects where it's present. Remove unnecessary jars from classpath or add above in class path. Now it will pick up correct one.
I ran into similar issue.
Caused by: java.lang.NoSuchMethodError: com.abc.Employee.getEmpId()I
Finally I identified the root cause was changing the data type of variable.
Employee.java --> Contains the variable (EmpId) whose Data Type has been changed from int to String.
ReportGeneration.java --> Retrieves the value using the getter, getEmpId().
We are supposed to rebundle the jar by including only the modified classes. As there was no change in ReportGeneration.java I was only including the Employee.class in Jar file. I had to include the ReportGeneration.class file in the jar to solve the issue.
I've had the same problem. This is also caused when there is an ambiguity in classes. My program was trying to invoke a method which was present in two JAR files present in the same location / class path. Delete one JAR file or execute your code such that only one JAR file is used. Check that you are not using same JAR or different versions of the same JAR that contain the same class.
DISP_E_EXCEPTION [step] [] [Z-JAVA-105 Java exception java.lang.NoSuchMethodError(com.example.yourmethod)]
Most of the times java.lang.NoSuchMethodError is caught be compiler but sometimes it can occur at runtime. If this error occurs at runtime then the only reason could be the change in the class structure that made it incompatible.
Best Explanation: https://www.journaldev.com/14538/java-lang-nosuchmethoderror
I've encountered this error too.
My problem was that I've changed a method's signature, something like
void invest(Currency money){...}
into
void invest(Euro money){...}
This method was invoked from a context similar to
public static void main(String args[]) {
Bank myBank = new Bank();
Euro capital = new Euro();
myBank.invest(capital);
}
The compiler was silent with regard to warnings/ errors, as capital is both Currency as well as Euro.
The problem appeared due to the fact that I only compiled the class in which the method was defined - Bank, but not the class from which the method is being called from, which contains the main() method.
This issue is not something you might encounter too often, as most frequently the project is rebuilt mannually or a Build action is triggered automatically, instead of just compiling the one modified class.
My usecase was that I generated a .jar file which was to be used as a hotfix, that did not contain the App.class as this was not modified. It made sense to me not to include it as I kept the initial argument's base class trough inheritance.
The thing is, when you compile a class, the resulting bytecode is kind of static, in other words, it's a hard-reference.
The original disassembled bytecode (generated with the javap tool) looks like this:
#7 = Methodref #2.#22 // Bank.invest:(LCurrency;)V
After the ClassLoader loads the new compiled Bank.class, it will not find such a method, it appears as if it was removed and not changed, thus the named error.
Hope this helps.
The problem in my case was having two versions of the same library in the build path. The older version of the library didn't have the function, and newer one did.
I had a similar problem with my Gradle Project using Intelij.
I solved it by deleting the .gradle (see screenshot below) Package and rebuilding the Project.
.gradle Package
I had faced the same issue. I changed the return type of one method and ran the test code of that one class. That is when I faced this NoSuchMethodError. As a solution, I ran the maven builds on the entire repository once, before running the test code again. The issue got resolved in the next single test run.
One such instance where this error occurs:
I happened to make a silly mistake of accessing private static member variables in a non static method. Changing the method to static solved the problem.

How can I run lombok features in my executable jar file?

Consider I have a constructor of more that 10 or more args, and I am using it in criteria select query to fetch data.
Now the problem is that I want to remove my constructor as it gives me sonar issues.
So I tried to Lombok dependency, #AllArgsConstructor it is working in my IDE,
but when I create the jar file it is not being used by JPA query.
I need help either to make lombok work in my project.jar file,
OR
change in select query which does not use constructor,
OR
Any other better way
Lombok is a compile-time affair. Once your code is compiled (you have class files), lombok shouldn't be there / wouldn't be doing anything. Lombok is not a library in that sense. You don't ship 'javac' with your app either.
If lombok is part of the compilation, then lombok will do its thing. If it's not, then your compiler would generate an error; after all, it wouldn't know what #AllArgsConstructor is about. So, if you're not observing any compilation errors, lombok did its thing*.
Secondly, sonar is a linting tool. It's there to help you out. If it is 'telling you off' for writing code where you think it is the best way to do it, then tell sonar to stop complaining about it. It's a tool for you to use; not a prison.
You can use javap to check if the all-args constructor is there. If it is (it should be), then your question is actually: How do I make my JPA tooling use that constructor?
*) It is possible, but takes some work, to tell javac to have lombok's classes available, but NOT to run it as an annotation processor. But if you do manage that, then lombok wouldn't have transformed any of your classes. I assume that's not the case, as you need to go out of your way with lots of command line switches to make this happen.

SBT: Java Annotation Processors and compileIncremental error

I’m using the immutables.org and mapstruct annotation processors in my sbt project (I've moved them to subprojects, so they don't interfere with each other).
Sometimes, compiling my project fails in compileIncremental because the annotation processor would create a new file, but the compiler already read the previously generated file or I changed my interface in src/main/java but the (previously) generated sources still "implement" the old interface (they would be overwritten, but that happens only after processing the sources in src/main/java).
My workaround was to create a task that deletes the generated sources beforehand for which "(compile in Compile)" would depend on.
Is there another way to do this? like disabling compileIncremental for one single project? or specifying the order of compilation? (like first normal sources, then unmanagedSources)
Alternatively finding out if the sourceFiles really changed and only then deleting the generated sources would also work for me, but I’m not sure how to approach that.
Any help would be greatly appreciated!
Thanks,
Dominik

Could java reflection add method into class file that are not in java source file?

I'm digging into the source code of the deeplearning for java recently. There is such a class NeuralNetConfiguration in which there are tons of fields that all requires getters and setters. The NeuralNetConfiguration.java source code does not provide any, however.
When I open this project in IntelliJ, ctrl click on the usage of this class, which are methods mostly like, NeuralNetConfiguration.getNInput() or NeuralNetConfiguration.getKernelSize(), the IDE direct me to the compiled class file in which all the getters are defined for each of the field in this class.
Just wonder how this is done since I'm a new bee to java. Posts I found about java reflect suggest that reflect can not add method to a method to a class unless you wrote your own classloader. I check the deep learning for java project and I don't think they have done that.
What bothers me too from time to time is, IntelliJ starts to report errors that those getFields methods could not be resolved since they are not in the source file at all, especially after my building the project using IntelliJ instead of using mvn command line.
The magic happens with the #Data annotation on the class. This annotation is from Project Lombok. There is probably an annotation processor somewhere that hooks into the compiling process and generates these methods.

Eclipse 3.5+ - Annotation processor: Generated classes cannot be imported

I am using a 3rd party annotation processor for generating meta-data code (.java files) from the annotated classes in my project.
I have successfully configured the processor through Eclipse (Properties -> Java Compiler -> Annotation Processing) and the code generation works fine (code is automatically created and generated). Also, Eclipse successfully auto-completes the generated classes and their fields, without any errors. Let's say that I have a class "some.package.Foo" and that the generated meta-data class is "some.package.Foo_". By the help of auto-completion, I can get the following code in the Eclipse editor, without any errors:
import some.package.Foo_;
...
public class Test {
void test() {
Foo_.someField = null; // try to access a field from the generated class Foo_
}
}
However, as soon as I actually build the project (or just save the file since Build automatically is enabled), I get the error which tells that "some.package.Foo_" cannot be resolved.
It seems like Eclipse is generating and compiling the some.package.Foo_ at the same time, or more likely.
I found two temporary solutions (which are practically hindering the use of the annotation processor in the first place):
Before each build of that generated classes, right click on every generated file go to Properties and uncheck the "Derived" tick. After that, I do the cleanup of the project and the imports are fine - there are no more errors. However, if I do the cleanup one more time, the errors again show up, because the generation of the files causes the "Derived" tick to be checked again (automatically). So this is really annoying and time-consuming.
I also uncheck the "Derived" tick
from all those files, and this time
I uncheck the "Derived" tick from
the source folder and packages which
contain those files. Then I disable
the annotation processor, and then
do the cleanup. There are no more
import errors, even if I do another
cleanup, but there is no benefit of
using the annotation processor,
because if I was to change something
which would update the model, I need
to turn the annotation processor
back on, and repeat this tedious
procedure to turn it off, after it
has generated the new version of
those files.
Is this a bug in Eclipse? If yes, is there a better workaround or quick-fix than the two I have stated above? If not, what should I try to solve the problem?
I also tried rearranging the order of the libraries on the build path and it doesn't help.
I assume that you are generating sources in the last processor round. This is not recommended way and leads exactly to the problem that you had.
Explanation is here: http://code.google.com/p/acris/wiki/CodeGenerationPlatform_Pitfall_Rounds
So the my advise is to generate sources in regular processing rounds and final round should be used just for notification that processing is over or something like that.
Hopefully this helps you.
I have a similar problem, and the only thing I've found is that it's the imports specifically that don't work, but the references in the class itself do work. The workaround I've used is to use the FQCN in all cases where the generated class is needed (except when the generated class is in the same package, since then the import is obviously not needed).
So to use your example, I'd do:
public class Test {
void test() {
some.package.Foo_.someField = null; // try to access a field from the generated class Foo_
}
}
My only guess then is that the eclipse compiler is processing the imports before doing the annotation processing, which imho must be a bug in eclipse.
I know this question is over a year old, so I'd be interested to know if you've found any other way to fix it.
We were experiencing a similar problem and apparently just solved it, so thought of sharing it at SO, in case it helps someone.
We are using:
Eclipse Indigo (Build id: 20120216-1857)
m2e Connector for maven
openJPA for static metamodel class generation
Our problem:
Say, we have a package named com.abc.xyz and an entity class in there named OurEntity. When we build the projects (JPA, EJB, EAR etc. all together with an mvn clean at the beginning) the metamodel classes get generated. And also get appropriately packaged within the PU jar. But when we try to import the generated metamodel class com.abc.xyz.OurEntity_, Eclipse cannot resolve it. OP apparently got past this point:-). Maven build failed, saying it could not resolve that class. Not much help from google except for a few bug reports such as this one: https://bugs.eclipse.org/bugs/show_bug.cgi?id=350378
That bug report said importing the whole package as opposed to the single class helped. So, tried that, but with no benefit. It also said (and so did David Heitzman) that using the fully qualified class name worked for them. That did not work either.
The solution:
Added the PU jar to Eclipse build path for the project that needed to use the metamodel classes. All of a sudden all the red underlines went away (not a surprise). But the fear was there might be two PUs in the same ear. But maven automagically took care of that.
As this rather old question got some attention without pointing to the very probable eclipse bug the OP was specifically asking for, I'd like to complement the above answers with a pointer to the eclipse bug tracker:
Cannot resolve import for generated class IF processing annotations with parameters referencing constants
The workarounds include
doing a wildcard import of the package defining the generated classes (i.e. import some.package.*;)
using the fully qualified name of your generated class, i.e. referring to some.package.Foo in your code and not using an import
switch to a newer Eclipse. This specific eclipse bug is resolved with Eclipse version 4.4 (aka Luna).

Categories