Java
public class print {
public static char getNum() throws Exception{
String method = print.class.getSimpleName()+Splitter.class.getDeclaredMethods().length;
try{
return (char)Splitter.class.getMethod(method).invoke(null);
}catch(Exception e){return ' ';}
}
}
class Splitter{
public static char print1(){
return PrinterP.printgetNum();
}
}
class PrinterP{
public static char printgetNum(){
String s = Thread.currentThread().getStackTrace()[2][P.class.getDeclaredMethods().length].getMethodName();
return s.charAt(s.length()-1P.class.getSimpleName().length());
}
public void doNothing(){}
}
Can be adjusted to return any other positive number n
by adding the methods printX
for X
from 1 to n into Splitter. For example, modifying Splitter
to
class Splitter{
public static char print1(){
return P.getNum();
}
public static char print2(){
return P.getNum();
}
}
Will return '2', without any other changes necessary. The added methods should, apart from the name, be an exact duplicate of print1
. Uses
Uses reflection to get the number of methods in splitter, and call a function with that name. Printer.printP.getNum
, which is then called, reads the stack trace and parses out the last character in the calling method, and displays it.
Calling print.getNum()
return the character '1'
Edit - modified to use no String/integer/etc literals.