开发者

Java & Android: Accessing a function using Classname vs this

I'm not sure if this is a Java related question or an Android related开发者_StackOverflow question, please let me know which one it is. Obviously I am trying to develop for the Android, and I am using Eclipse.

Within a java class MainThread I have declared a constant.

This declaration works: private static final String TAG = MainThread.class.getSimpleName();

But this does not: private static final String TAG = this.class.getSimpleName();

Why is it that using the 2nd method returns the error: Syntax error on token "class", Identifier expected


Well, this.class simply isn't valid Java. In particular, using this in a static context (such as a static variable initializer) makes no sense.

If you're looking for something you can cut and paste from class to class without having to worry about the classname changing, there's no syntax in Java which will let you do that I'm afraid. There are tricks available via capturing stack traces on desktop Java but they may well not work on Android. I'd stick with specifying the class name explicitly if I were you.

(It's possible that this.class is meaningful in the context of a nested type. There's all kinds of weirdness there, and I can never remember it - but it's not useful here.)


In Java there are two types of class members. Static members, or instance members. A static member is associated with the type, or class. An instance member is associated with an instance of the class (i.e. an object). In both cases you are defining static fields in your class. The implicit this variable is an instance member of a class and static code cannot reference instance members.

So the reason the second example gives an error is that there is no instance of the class at the time you reference this so this cannot be resolved.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜