我是靠谱客的博主 自觉小笼包,这篇文章主要介绍java 自己定义的静态方法_java使用静态方法得到自己的类名,现在分享给大家,希望可以做个参考。



正常的得到类明的方法是:

String clazz = this.getClass().getName();

但这种方法无法在下面静态方法中使用

public static void main(String[] args){

//...

}

那么在main中就不能得到类的名称

下面的类解决了这个难题

package madaming.io.systemoutprints;

/**

* Created by madaming on 2014/11/5.

*/

public class Names {

public static final String getClassName() {

int stackLength = Thread.currentThread().getStackTrace().length;

return Thread.currentThread().getStackTrace()[stackLength - 1].getClassName();// 堆栈中最后一项一定是调用类

}

public static final String getClassSimpleName() {

String className = getClassName();

return className.substring(className.lastIndexOf(".") + 1);

}

}

package madaming.io.systemoutprints;

import java.io.*;

import java.text.SimpleDateFormat;

import java.util.Date;

public class Files {

public static void main(String[] args) {

Thread t = Thread.currentThread();

String className = Names.getClassName();

String classSimpleName = Names.getClassSimpleName( );

System.out.println(df.format("全类名:"+className);

System.out.println(df.format("简单类名:"+classSimpleName);

}

}

最后

以上就是自觉小笼包最近收集整理的关于java 自己定义的静态方法_java使用静态方法得到自己的类名的全部内容,更多相关java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(114)

评论列表共有 0 条评论

立即
投稿
返回
顶部