spoon icon indicating copy to clipboard operation
spoon copied to clipboard

How would one obtain getType of CtInvocation which is a lambda expression?

Open djaekim opened this issue 2 years ago • 1 comments

For example,

assertThrows(NullPointerException.class, () -> getPredicateInstance(new Predicate[] { null }));

I want to obtain return type of getPredicateInstance

This function is an abstract function defined prior as shown here: protected abstract Predicate<T> getPredicateInstance(Collection<Predicate<T>> predicates);

Currently, it is returning null. I was wondering if there is any work around I can try?

Thank you so much, Kim

djaekim avatar Sep 16 '22 13:09 djaekim

I can't really confirm:

	@Test
	void foo() {
		Launcher launcher = new Launcher();
		launcher.addInputResource(new VirtualFile("\n" +
			"import java.util.*;\n" +
			"import java.util.function.*;\n" +
			"import java.util.concurrent.*;\n" +
			"  abstract class Foo<T> {\n" +
			"    protected abstract Predicate<T> getPredicateInstance(Collection<Predicate<T>> predicates);\n" +
			"    public static <R> void assertThrows(Class<?> clazz, Callable<R> r) {}\n" +
			"\n" +
			"    public void bar() {\n" +
			"      assertThrows(NullPointerException.class, () -> getPredicateInstance(List.of(new Predicate[]{null})));\n" +
			"    }\n" +
			"  }\n"));
		launcher.getEnvironment().setComplianceLevel(17);
		launcher.getEnvironment().setShouldCompile(true);
		launcher.run();
		CtClass<?> ctClass = launcher.getFactory().Class().get("Foo");
		CtMethod<?> bar = ctClass.getMethodsByName("bar").get(0);
		CtInvocation<?> throwsStatement = bar.getBody().getStatement(0);
		CtLambda<?> lambda = (CtLambda<?>) throwsStatement.getArguments().get(1);
		System.out.println(lambda.getExpression());
		System.out.println(lambda.getExpression().getType());
	}

prints

getPredicateInstance(java.util.List.of(new java.util.function.Predicate[]{ null }))
java.util.function.Predicate<T>

Maybe your code does not compile? Can you try adding

		launcher.getEnvironment().setShouldCompile(true);
		launcher.run();

to see whether compilation of your code fails?

I-Al-Istannen avatar Sep 18 '22 21:09 I-Al-Istannen