How to create import in generated java files? - java

I'm working with an API that generate a lot of java code to me.
But this API does not handle import correctly, so it write full qualified name of every class. eg:
public class Foo{
com.my.company.Bar bar;
public com.my.company.Bar getBar(){
return bar;
}
}
I would like to find an API to post process this generated code and write something like that:
import com.my.company.Bar;
public class Foo{
Bar bar;
public Bar getBar(){
return bar;
}
}
Is there any known API able to do that?

Filtering imports from existing code isn't trivial; imagine you have two classes with the same name but different package.
My usual approach is to have a helper class which manages the imports for me. In the generator, I can
String type = importSet.add(Foo.class);
type is then used in the method to access the type. The import set collects all imports and handles duplicates.
For this to work, you need this "main loop":
importSet = new ImportSet();
String body = generateClass();
out.write(importSet);
out.write(body);
i.e. you need to generate all the code for the class itself (collecting the imports as you go) first. Then you write the imports to the file and after that the generated class body.
If you want to change the sources, I suggest to use the Eclipse Java compiler because it can give you the AST of the code. You can then apply various transformations on this tree. I have an example in my blog how to get the AST.

As far as I see you expect to generate Java code right? If yes . We are using Eclipse JDT in our project which is from Eclipse IDE and they use it for Java code generation. And I encourage to use it, however depending on need you might go for simple solution like QDox or even other solution.
You can consider either one of the solution
Eclipse JDT
Javaparser
Qdox
Eclipse JDT
Pros
Impressive functionality
Very rich API
Support for Java 7 features and they have a plan to also support Java 8 features
Localizable syntax error messages
Con's
Steep learning curve
Resources
Intro to Eclipse JDT
http://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_AST/index.html
How to use JDT API outside eclipse
How can I use the java Eclipse Abstract Syntax Tree in a project outside Eclipse? (ie not an eclipse plugin)
Nice example and project on AST
http://www.ibm.com/developerworks/opensource/library/os-ast/
Access Eclipse jar plugin sources
http://www.vogella.de/articles/EclipseCodeAccess/article.html
Test samples
http://git.eclipse.org/c/jdt/eclipse.jdt.core.git/tree/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests
Qdox
Pro's
build from scratch and modify
lightweight
FQN type based searching
clean and readable API
extensive querying possibility like isFinal(), isPrivate()
object oriented constructs, almost everything in a java file can be represented in terms of objects like, JavaClass, JavaField, JavaMethod, JavaParmeter
Con's
last public release was 1.10 on 2009-09-04, how ever 2.0 snapshot is available
1.10 is not supporting static import;
writing to a file is pre-formatted, don't have much control over it, can't specify the line numbers
no article or tutorial, source code is the only reference
Resources
- Qdox http://qdox.codehaus.org/changes-report.html

Related

Find out used classes and methods from Java source code

For Java source files, I would like to find out:
Which classes use which other classes (fully qualified names)?
Which methods call which other methods (fully qualified names)?
What would be a reasonable way to achieve that?
EDIT:
To clarify: I want a list of source code files as input. The output should be (as specified above) which class uses which other class and which method calls which other method. I do not want to inspect other loaded classes at runtime, like when using reflection.
You need to use static analysis tool as STAN standalone mode:
The standalone application is targeted to architects and project managers who are typically not using the IDE.
Or JArchitect (available also using command line)
JArchitect is a powerful tool for static code analysis. It can provide a lot of insight into complex code bases. Using custom code queries you are able to build your own rule sets in a very comfortable way.
In the Class Browser right-click menu, JArchitect proposes to explore the graph of dependencies between members (methods + fields) of a type.
Another option is SourceTrail
The graph visualization provides a quick overview of any class, method, field, etc., of interest and all its relations. The graph is fully interactive. Use it to move through the codebase by focusing on related nodes and edges.
(source: sourcetrail.com)
Unfortunately, reflection doesn't give you all the information you need to do this.
I've done it with ASM (https://asm.ow2.io/).
It provides the ability to walk the byte code of all of your classes using the visitor pattern, including the actual method implementations, from which you can extract the references to other classes.
I'm sorry that I cannot provide the implementation, because it's proprietary.
Note that this works from your .jar files, not your sources. If you really need to work from sources, then have a look at https://github.com/javaparser . Really, though, it's better to use the byte code, since the java language changes frequently, while the byte code specification does not.
I am not sure how to get a listing, but for identifying refactoring opportunities, you might try IntelliJ IDEA. It will dull out the signature line of any methods that are not accessed in the project. It will also detect code segments that are repeated elsewhere in the project, so you can extract common code.

Manipulating Java classes with Java

I would like to manipulate Java classes (with java extension not .class) so that I could :
Delete all methods of a class (keeping the constructor)
Add unimplemented methods
Remove unused imports
...
Is there an API that could accomplish this ?
What I've done so far is trying to manipulate the .java files like text files (with regex,FileUtils, etc.).
Regards.
I
You could look at using the AST (Abstract Syntax Tree) tools from the Eclipse JDT project.
There is a tutorial to get you started at Vogella: Eclipse JDT - Abstract Syntax Tree (AST) and the Java Model - Tutorial
If you only want to temporarily modify the classes (i.e. within the scope of the jvm) then you could do this with reflection:
What is reflection and why is it useful?
If you're taking about permanently altering/creating source code then this is maybe best done using an IDE. Most IDE will tell you about unimplemented methods and provide auto completion to create them. They will also format the source code, remove unused imports etc.
You can use a regular expression, the question then is then what regular expression (And what other options are there!)
Regular expressions maybe aren't ideally suited to this, and for example, when it comes to another task they're not ideally suited to, such as parsing XML, people say don't do it, use an XML parser, but in this case, if you find that there is an absence of a tool built for parsing java source code, then regular expressions may be the best option.
Yes, you can use java reflection api. Please check here
Later edit: To update the class structure you can use javassist. Here you have an example.

How to import DLL into the JAVA project in Eclipse?

There is DLL file called as myAPI.dll. It contains classes that I'd like to use in my JAVA code. How to import this DLL file into my Java project in Eclipse? It should be possible to run the code based on something like this:
import myAPI;
public class MyClass {
//...
}
}
I do not know which language is used for your code snippet but it is definitely not java. Java does not have keywords like using and namespace.
Generally to call native code from java you have to use good old JNI or newer JNA.
Please follow the following links to get started with these technologies.
http://java.sun.com/docs/books/jni/html/start.html
http://www.javaworld.com/community/node/1767
The code snippet you have shown is C#, not Java. Now namespace lets you group logically related things. For e.g. all order processing related classes can be put under single namespace. It is also used as a mechanism to avoid/resolve name conflicts. It also defines the visibility scope of your class. Read this lesson for more details.

Is there a way to link JDK annotations to requirements?

Hi guys: Is there an open source way to associate java #annotations to functional requirements, or for example, TRAC tickets, etc? I want to do something like this:
I'm thinking along the lines of an eclipse plugin which somehow links up with another FOSS project tracking tool, wiki, or maybe even a CSV file.
A somewhat silly but exemplary illustration of what I desire is below:
#Requirement WalkDogTwiceADay
public void walkTheDog()
{
}
#Requirement WalkDogTwiceADay
public void dogWalkerThread()
{
walkTheDog(); //in the morning.
Thread.sleep(36000000);
walkTheDog(); //at night
}
Annotations are metadata, they simply add information to your code for other tools to use or to be inspected at runtime via reflection.
One thing you can do is write an annotation processor that will generate the necessary artefacts. Those could be configuration files, scripts, code...
Another thing you can do is write some tool that knows how to interpret your annotations and uses reflection to find them and take the appropriate actions. For this you'd need to make sure that the annotation type is set to have runtime retention, as opposed to only source or class.
Perhaps some of the stuff found in the answers to this question might prove of use. If that's the case, go ahead and use it. But writing custom annotation processors or code for handling them is not all that terribly hard. The difficult part is getting to know the Java model API that's used by annotation processors, which is like reflection but at compile time (before you have fully-formed classes).
in a previous life, we did something similar with #requirement ##### annotations, and then had a custom javadoc task that turned the requirement annotations into hyperlinks in the javadocs.
I was going to write an addin for eclipse that turned them into links in the code as well, but never got that far.

Java source code parser which supports annotations

I need a Java source code parsing library for Java to programmatically extract method definitions and annotations.
Specifically, given code like :
#WebMethod(operationName = "MyOperation")
public String myOperation(String param1,int param2) { ....
}
I have the following requirements:
1. Extract the name, return type and names and types of the method parameters
2. Extract the annotations associated with the method
3. Finally, create a new source file by removing the annotations
I am currently using JaxMeJS http://ws.apache.org/jaxme/js/jparser.html which satisfies 1. but not 2. or 3.
Could you recommended a parsing library that can fulfill all 3 requirements ?
JavaCC comes with a 1.5 parser.
Annotation processing is part of the Annotation processing tool in Java which runs as part of the Java compiler. I'm not sure how you can remove the annotations from the source code. This is not supported by APT. (It might be easier to remove the annotations from the compiler byte code than from the source code.)
I've implemented a source code generator based on annotations using APT in the Quickcheck project.
Another root could be to use ASM (or any other byte code manipulation tool) to read the annotations.
I think APT, as suggested by Thomas Jung is what you need. Still, if you want to look into other options, do check Java 6 grammar for antlr
How about using JDT parser?
JDT means Java Development Tools.
Eclipse use this.
I also did my project with it.
It is really nice. And there is much info about it.

Categories

Resources