0

When using Class.forName() in the Groovy-Script of an IntelliJ-Live-Template-Variable always the name of the determined class is returned and the execution of the remaining code is stopped. This behaviour differs from the behaviour when running the same code in the Groovy-Console. I think this is, because the for name method is a static one and the groovyScript()-Method in the Live-Templates cant handle static methods the right way.

This is my Groovy code:

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.stream.Collectors;

def result = '';

String clsName = _1.substring(0, Math.min(_1.lastIndexOf('Test'),_1.length())).replace('integration.', '');
Class<?> cls = Class.forName(clsName);
List<Method> methods = cls.getDeclaredMethods().toList();
List<String> methodNames =methods.stream().filter(m -> Modifier.isPublic(m.getModifiers())).map(m -> m.getName()).collect(Collectors.toList());
result = '\"'+methodNames.toString().replace('[','').replace(']','').replace(', ', '\",\"')+'\"';
println(result);
return result;

And this is my Code as Live-Template-Variable-Expression:

groovyScript("import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.stream.Collectors;  def result = '';  String clsName = _1.substring(0, Math.min(_1.lastIndexOf('Test'),_1.length())).replace('integration.', ''); Class<?> cls = Class.forName(clsName); List<Method> methods = cls.getDeclaredMethods().toList(); List<String> methodNames =methods.stream().filter(m -> Modifier.isPublic(m.getModifiers())).map(m -> m.getName()).collect(Collectors.toList()); result = '\"'+methodNames.toString().replace('[','').replace(']','').replace(', ', '\",\"')+'\"'; println(result); return result;",qualifiedClassName())

Notice that i use the qualifiedClassName-Method to get the class-name of the current test file. Then i remove the test postfix and a potential integration. package to get the qualified name of the tested class.

Is there any way to obtain a classes methods without using a static method or is there any way to run static methods in my groovy-script.

Thx for your answers and have a nice weekend.

Nico S.
  • 77
  • 1
  • 1
  • 9
  • 1
    I'd recommend you report this issue at https://youtrack.jetbrains.com/issues/IDEA so that IDEA developers could take a look at it. – Egor Klepikov Jun 24 '22 at 09:47
  • "is there any way to obtain a classes methods without using a static method" - I think the only static methods you are using in the Groovy code are `Class.forName`, `Math.min`, and `Collectors.toList`. Are you trying to eliminate those? – Jeff Scott Brown Jun 24 '22 at 12:17
  • 1
    (I missed `Modifier.isPublic` as another static method) – Jeff Scott Brown Jun 24 '22 at 16:13

0 Answers0