Get IMethod from the method name in java - java

I'm looking for a way to find the IMethod, given the method name as input for developing my eclipse plugin further.
Couldn't figure out a way to do so.
can someone please direct me in the right path.

There can be two approaches:
You can use the ASTVisitor pattern to visit the MethodDeclaration nodes, do a check for name and arguments, and get IMethod from them by resolving the binding. Refer the below posts:
Eclipse create CompilationUnit from .java file
How to convert AST to JDT Java model
Get the ITypes from the compilation unit and loop through the IMethods, do check for name and arguments to find the required one.
IType [] typeDeclarationList = unit.getTypes();
for (IType typeDeclaration : typeDeclarationList) {
// Get methods under each type declaration.
IMethod [] methodList = typeDeclaration.getMethods();
for (IMethod method : methodList) {
// Logic here.
}
}

Related

How to split the string using comma delimiter in Jenkins Groovy script?

I have tried to get all the solution files(*.sln) in a given path and print it individually by split the string(each solution file path) using comma delimiter. Programming script language am using is Jenkins Groovy. Am getting the below specified error when build the Jenkins job. Any one please look into this and guide me to proceed in a right way.
def finder = new FileNameFinder()
def files = finder.getFileNames 'D:\jobs', '**/*.sln'
def resultList = files.tokenize(",")
for(i=0; i<resultList.size();i++)
{
println resultList[i]
}
Error Details:
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.tokenize() is applicable for argument types: (java.lang.String) values: [,]
Possible solutions: toUnique(), toUnique(), toUnique(java.util.Comparator), takeWhile(groovy.lang.Closure), toUnique(groovy.lang.Closure), toUnique(java.util.Comparator)
Thanks in advance!!
Myself itself found an answer for my above problem. Please find below the modified working code.
def finder = new FileNameFinder()
def files = finder.getFileNames 'D:\jobs', '**/*.sln'
assert files instanceof List
println files.size()+" solution files found in the given path. Below are the found solution files details. \n"
for(i=0;i<files.size();i++)
{
println files[i];
}
Thanks

Cannot find symbol '/' in class name

When I compile my java class. There are some errors of cannot find symble '/' in class name. Below is a sample code from my class:
public TransactionSearchResponse submit(TxnSearchRequest req)
{
url = (new StringBuilder(String.valueOf(req.getBaseUrl()))).append("/txns/search").toString();
method = "POST";
return (TransactionSearchResponse)sendRequest(req, com/COMPPONENT/api/TransactionSearchResponse);
}
Be cause of copyright from author of this code block. sendRequest Method is deleted.
Netbeans cannot recognize the dash '/' in the class name "com/COMPPONENT/api/TxnResp". And the class name contains some parts:
Package name: com.COMPONENT.api
Class name: TxnResp
Java file name: TxnResp.java
The dash '/' show in red color as Netbeans mask it an error line. The only hint I got from Netbeans are "Add import for com.COMPONENT.api.TxnResp" or "Flip Operands of '/' (may alter semantics), and I did that but got no luck. And when I try to run the code, it generate an error of "Cannot find symbol". Can you help me to solve this issue?
Regards,
Dung Tri
If a method sendRequest is declared like
Object sendRequest( Request x, Class<?> y )
you'll have to call it with an instance of a java.lang.Class object:
... = sendRequest( request, com.COMPPONENT.api.TxnResp.class );
Appending .class is the way of obtaining an instance of a certain Class object (not to be confused with an instance of TxnResp which is created using new TxnResp).
Also, given
com.COMPPONENT.api.TxnResp txnResp = new com.COMPPONENT.api.TxnResp();
the expression
txnResp.getClass()
results in an instance of the Class<com.COMPPONENT.api.TxnResp> but of course the .class notation is more convenient for your purpose.

AST eclipse, adding arguments to a MethodInvocation

Im trying to add arguments to the arguments list of a MethodInvocation and it doesnt seem to work, I can remove objects but I cant see to add them.
My end goal is to take 2 MethodInvocation that invoke the same method with different arguments and convert it to 1 MethodInvocation that has a ConditionalExpression as an argument.
Example:
if (A){
System.out.println("hi");
} else {
System.out.println("hey");
}
Will be converted to:
System.out.println((A ? "hi" : "hey"));
So I would also appreciate it if someone knwos how to convert the argument list to 1 big Expression I can place in the ConditionalExpression.
Thanks!
EDIT: sorry forgot to mention is it a code formatting plug-in for ecplise
EDIT2: the code I am trying to run:
final ExpressionStatement thenStmnt=(ExpressionStatement)((Block)node.getThenStatement()).statements().get(0),
elseStmnt=(ExpressionStatement)((Block)node.getElseStatement()).statements().get(0);
MethodInvocation thenMethod=(MethodInvocation)thenStmnt.getExpression(),
elseMethod=(MethodInvocation)elseStmnt.getExpression();
final MethodInvocation method=ast.newMethodInvocation();
method.setName(ast.newSimpleName("add"));
method.arguments().add(0, elseMethod.arguments().get(0));
ast is a given leagal AST and node is a given leagal IfStatement.
Solved, problem was here:
method.arguments().add(0, elseMethod.arguments().get(0));
If you want to take or copy something that is already part of your original code, meaning already exist in the AST you have to use r.createCopyTarget, like so:
method.arguments().add(0, r.createCopyTarget(elseMethod.arguments().get(0)));

Get the type of a FieldDeclaration in AST

I am working with a Java AST. How can I get the Type (e.g. String or MyOwnType) of a FieldDeclaration or VariableDeclaration? In ASTView I can see it under SimpleName > type binding, but with getters I cannot reach the member.
I tried the solution from FieldDeclaration to IField - Getting IBinding from FieldDeclaration but resolveBinding returns null when visiting the FieldDeclaration.
Why does resolveBinding() return null even though I setResolveBindings(true) on my ASTParser? not working either
Wow, this was tough.
The last line made it possible to resolve the bindings and retrieve the type via varDeclFrag.resolveBinding().getType().getQualifiedName(); although I already thought I did the same in setEnvironment when referring to sources:
String[] sources = { "C:\\a\\TheMightyExampleProject\\src" };
String[] classPaths = { "C:\\a\\antlr-4.1-complete.jar" };
parser.setEnvironment(classPaths, sources, new String[] { "UTF-8" }, true);
parser.setBindingsRecovery(true);
parser.setResolveBindings(true);
parser.setCompilerOptions(options);
parser.setStatementsRecovery(true);
parser.setUnitName("C:\\a\\TheMightyExampleProject\\src"); // ftw
You can also check out the answer of Ida bindings not resolving with AST processing in eclipse

Get unresolved imports

I'm writing eclipse plugin that looks for unresolved imports in all source files.
I found that it can be helpful to use IProblem or IMarker objects. Here's code example
public IMarker[] findJavaProblemMarkers(ICompilationUnit cu)
throws CoreException {
IResource javaSourceFile = cu.getUnderlyingResource();
IMarker[] markers =
javaSourceFile.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER,
true, IResource.DEPTH_INFINITE);
}
frome here
I don't know how I can get info from IProblem or IMarker about which import cause the compilation problem (unresolved import).
Any help?
http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.jdt.doc.isv/guide/jdt_api_classpath.htm
There are a list of different int values in the IProblem interface representing different errors; if you could get the errorcodes of a file somehow, you could use them. (Example, ImportNotVisible, ImportNotFound, etc.). Just check if the error ID matches one of the error ID's for import failures there.
An IMarker knows the line number and start and stop chars for the java source marked by the IMarker. You can take the substring of the java source string and, if the marker type indicates that it's a problem with the class or import, you can search the project's classpath for a class or package matching (or similar to) that substring.

Categories

Resources