faint! Such a freak question. even if it's possible (who knows, there might exists some class in jdk that can provide information on runtime stack), it's only a hacking technique.Or, to make a joke, add a class and a static variable to store the name, like public class StupidContext { public static String stupidName; }public class Test { public static void main(String[] args) { StupidContext.stupidName = "Test"; ShowClassName.Show(); } }class ShowClassName { public static void Show() { System.out.println(StupidContext.stupidName); ... } }ha ha ha!
Test t=new Test(); System.out.println(t.getClass().getName());这样肯定可以了
why not System.out.println(Test.class.getName()); or even System.out.println("Test")? more straight-forward. :->
that's why I said it's "freak question". I was only saying that dynku's solution is no different than simply print "Test". not worth time to think it.
try { throw new RuntimeException("this is a bad hack!!!!!"); } catch(Throwable t) { StackTraceElement[] trace = t.getStackTrace(); System.out.println(trace[1].getClassName()); }and it only works in jdk1.4 What a "Wu Ren Zi Di" question!
Such a freak question.
even if it's possible (who knows, there might exists some class in jdk that can provide information on runtime stack), it's only a hacking technique.Or, to make a joke, add a class and a static variable to store the name, like
public class StupidContext
{
public static String stupidName;
}public class Test
{
public static void main(String[] args)
{
StupidContext.stupidName = "Test";
ShowClassName.Show();
}
}class ShowClassName
{
public static void Show()
{
System.out.println(StupidContext.stupidName);
...
}
}ha ha ha!
System.out.println(t.getClass().getName());这样肯定可以了
or even System.out.println("Test")?
more straight-forward.
:->
假如是"Test1"调用呢?或者一个程序有两个类或多个类调用呢?你怎么办?呵呵,再想想吧。to dynku(随风来去.cn):
程序若没有"Test"类而改成"Test1"怎么办呢?或者一个程序有两个类或多个类调用呢?题目意思是Show()可以被任何类调用都可得知调用者。
I was only saying that dynku's solution is no different than simply print "Test".
not worth time to think it.
{
throw new RuntimeException("this is a bad hack!!!!!");
}
catch(Throwable t)
{
StackTraceElement[] trace = t.getStackTrace();
System.out.println(trace[1].getClassName());
}and it only works in jdk1.4
What a "Wu Ren Zi Di" question!
class ShowClassName
{
public static void Show()
{
Exception e=new Exception();
StringWriter bo=new StringWriter();
PrintWriter ps=new PrintWriter(bo);
e.printStackTrace(ps);
String s=new String(bo.getBuffer()); //下面即可处理输出的字符串了。
}
}
不知道还有没有其他的方法,考试是仓促这题我没得满分,呵呵。