@Retention(RUNTIME)
@Target(METHOD)
public @interface Test {
String[] value() default {};
}
@Retention(RUNTIME)
@Target(METHOD)
public @interface PrintIt {
String[] value();
}
public final class Main {
public static void main(String[] args) throws Throwable {
Method method = null;
for (var m : Solution.class.getDeclaredMethods()) {
if (m.isAnnotationPresent(Test.class)) {
method = m;
break;
}
}
if (method == null) {
System.out.println("Solution has not @Test method!");
return;
}
var value = method.getAnnotation(Test.class).value();
var objs = new Object[value.length];
var solu = new Solution();
for (var i = 0; i < value.length; i++) {
var field = Solution.class.getDeclaredField(value[i]);
field.setAccessible(true);
objs[i] = field.get(solu);
}
var rtn = method.invoke(solu, objs);
if (method.getReturnType() != void.class) {
println(rtn);
}
// print it
var pi = method.getAnnotation(PrintIt.class);
if (pi != null) {
value = pi.value();
for (var s : value) {
var field = Solution.class.getDeclaredField(s);
field.setAccessible(true);
println(field.get(solu));
}
}
}
static void println(Object obj) throws Throwable {
if (obj == null) {
System.out.println("null");
} else if (obj.getClass().isArray()) {
if (obj.getClass().getComponentType().isPrimitive()) {
System.out.println(Arrays.class.getDeclaredMethod("toString", obj.getClass()).invoke(null, obj));
} else {
for (var o : (Object[]) obj) {
println(o);
}
}
} else {
System.out.println(obj);
}
}
}
用例
public class Solution {
@Test("root")
@PrintIt("root")
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
var left = root.left;
root.left = root.right;
root.right = left;
invertTree(root.left);
invertTree(root.right);
return root;
}
TreeNode root = null;
}