Reputation: 494
I have a groovy file named sample.groovy
, which contains different methods:
class sample {
def doOperation()
{
println("Inside doOperation()")
}
def setData(String str)
{
println("Incoming data : " + str)
}
}
I have defined only 2 methods: doOperation()
and setData()
, and I want to list out these 2 methods only.
I have used reflection and try to list out methods using getDeclaredMethods()
. But it list out above methods and methods like: setProperty
, getProperty
, setMetaClass
, etc.
I want to list out the methods defined in this particular file only.
Upvotes: 3
Views: 3094
Reputation: 853
You should try below to get only your methods instead of inherited methods :-
def myMethods = MyClass.declaredMethods.findAll { !it.synthetic }
Hope it will help you...:)
Upvotes: 1
Reputation: 12086
According to JLS 13.1.7, the "Groovy" methods that are generated should be marked as synthetic:
Any constructs introduced by a Java compiler that do not have a corresponding construct in the source code must be marked as synthetic, except for default constructors, the class initialization method, and the values and valueOf methods of the Enum class.
With this in mind, you can filter out the synthetic methods on the class to give you only methods in the source code:
def methods = sample.declaredMethods.findAll { !it.synthetic }
If you're looking for a pure Java solution, you can do the following:
List<Method> methods = new ArrayList<>();
for (Method m : sample.class.getDeclaredMethods()) {
if (!m.isSynthetic()) {
methods.add(m);
}
}
Or using the Java 8 streams API:
List<Method> methods = Arrays.stream(sample.class.getDeclaredMethods())
.filter(m -> !m.isSynthetic())
.collect(Collectors.toList());
Upvotes: 2
Reputation: 140457
What you are asking for doesn't really make (too much) sense.
You see, the Java language knows nothing about the Groovy language.
The point is that Groovy source code will be compiled into JVM bytecode at some point.
This means: all the things that Groovy "adds" compared to the Java language ... are in the end, expressed as JVM bytecode.
In other words: the groovy compiler does its "magic" (for example by adding various methods); and all of that goes into the .class file. And when you then look "into" that .class ... you get all the things in there. As "java reflection" has no notion of "this method was really written by the groovy programmer" versus "this method was added by some groovy transformation process).
Long story short: if at all, you would need to look into mechanisms on the Groovy side of things; because only there you can know that "sample" has those two methods.
Upvotes: 1