I need to pass an instance of an anonymous class as a function parameter, in Spoon. In my case I have an anonymous Comparator that I need to pass to a function that gets Comparator<?> as a parameter.
Here's my code:
public boolean isToBeProcessed(CtType<?> candidate) {
if(candidate instanceof CtClass<?> && ((CtClass<?>)candidate).isAnonymous()==true){
CtClass<?> clas = (CtClass<?>)candidate;
List<CtMethod<?>> list = clas.filterChildren(
new AbstractFilter<CtMethod<?>>(CtMethod.class) {
@Override
public boolean matches(CtMethod<?> method) {
return method.getSimpleName().equals("compare");
}
}
).list();
return !(list==null || list.isEmpty());
}
return false;
}
@Override
public void process(CtType<?> element) {
// here I need to pass the anonymous Comparator class
testComparator( ??? );
}
public void testComparator(Comparator<?> comparator) {
......
}
I'm new to Spoon and I would appreciate your help with this.
Thanks.
I guess I managed to do what you asked.
dir/App.java
src/main/java/MyProcessor.java
src/main/java/Main.java
dir2/A.java
dir2/B.java
pom.xml
Also directory
spooned-classes
has to be added to classpath. I'm using sbt. This can be specified there asunmanagedClasspath in Runtime ++= Seq(file("spooned-classes")).classpath
. In Maven this should be specified similarly.Output:
So
testComparator
inMain
was executed twice corresponding tofoo1
andfoo2
inApp
.