请写出一个静态方法public static String getMyClassName(),使它满足:将这个方法放在任何一个类里面,它都能返回所在类的类名称。
比如把它放在类Narnia里面,这个方法就返回字符串“Narnia”;放在类Minerva里面,就返回字符串“Minerva”.
比如把它放在类Narnia里面,这个方法就返回字符串“Narnia”;放在类Minerva里面,就返回字符串“Minerva”.
return ste[0].getClassName();
public static String getMyClassName(){
return new Throwable().getStackTrace()[1].getClassName();
}
Class cl =Class.forName(name);
String r = cl.getName();
我觉得讨论 这么做的意义 比如何实现 有用。
private static String getClassName(){
return new Throwable().getStackTrace()[0].getClassName();
}
直接解决
这里new Throwable()你用new Exception()也是一样。
自己看下就知道,里面很多get方法,能拿不少东东
sun.reflect.Reflection.getCallerClass(1).getName();
另外有一种和上面差不多的写法,
Thread.currentThread().getStackTrace()[1].getClassName();
我想过this.class.getClassName(),一看是static方法,嗯。
这个是什么原理呢
StackTraceElement[] ste = new Throwable().getStackTrace();
return ste[0].getClassName();
如果是SUN JDK的话,还有一种写法:
sun.reflect.Reflection.getCallerClass(1).getName();
另外有一种和上面差不多的写法,
Thread.currentThread().getStackTrace()[1].getClassName();这些都是可行的
这个方法可以,不过我觉得这个问题本来就有问题,实现这种功能不应该用static方法来实现,如果不用static方法实现的话就好搞多了,而且放在基类里面继承下去,每个类就都有这个功能了。
使用反射分析类的能力
Class cl =Class.forName(name);
String r = cl.getName();
这个好像有些印象,应该没什么问题。