获取类 Class.getName()的唯一名称

我怎样才能知道这个班的名字

String.class.getName()  returns java.lang.String


我只对得到最后一部分(只有字符串)感兴趣
任何阿皮都能做到吗?

121085 次浏览

or programmaticaly

String s = String.class.getName();
s = s.substring(s.lastIndexOf('.') + 1);

Social.class.getSimpleName()

getSimpleName() : Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous. The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".

The below both ways works fine.

System.out.println("The Class Name is: " + this.getClass().getName());
System.out.println("The simple Class Name is: " + this.getClass().getSimpleName());

Output as below:

The Class Name is: package.Student

The simple Class Name is: Student

You can use following simple technique for print log with class name.

private String TAG = MainActivity.class.getSimpleName();

Suppose we have to check coming variable value in method then we can use log like bellow :

private void printVariable(){
Log.e(TAG, "printVariable: ");
}

Importance of this line is that, we can check method name along with class name. To write this type of log.

write :- loge and Enter.

will print on console

E/MainActivity: printVariable:

Get simple name instead of path.

String onlyClassName =  this.getLocalClassName();

call above method in onCreate

Here is the Groovy way of accessing object properties:

this.class.simpleName    # returns the simple name of the current class