最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Android(Java)中的const变量定义出错:Syntax error on token "const", delete this token

Android crifan 5231浏览 0评论

【问题】

在Android中想要定义一个const字符串,结果出错:

Syntax error on token "const", delete this token

Syntax error on token const delete this token

【解决过程】

1.搜了点资料,也没有说清楚的。

2.后来参考了这个,说的比较清楚:

Declare Constants Final

Consider the following declaration at the top of a class:

static int intVal = 42;
static String strVal = "Hello, world!";

The compiler generates a class initializer method, called <clinit>, that is executed when the class is first used. The method stores the value 42 into intVal, and extracts a reference from the classfile string constant table for strVal. When these values are referenced later on, they are accessed with field lookups.

We can improve matters with the "final" keyword:

static final int intVal = 42;
static final String strVal = "Hello, world!";

The class no longer requires a <clinit> method, because the constants go into classfile static field initializers, which are handled directly by the VM. Code accessing intVal will use the integer value 42 directly, and accesses to strVal will use a relatively inexpensive "string constant" instruction instead of a field lookup.

Declaring a method or class "final" does not confer any immediate performance benefits, but it does allow certain optimizations. For example, if the compiler knows that a "getter" method can’t be overridden by a sub-class, it can inline the method call.

You can also declare local variables final. However, this has no definitive performance benefits. For local variables, only use "final" if it makes the code clearer (or you have to, e.g. for use in an anonymous inner class).

所以去该代码为:

static final String  stHtmlCharset = "GB18030";

然后就可以实现,类似于const的效果了。

 

【总结】

把const xxx 改为:static final xxx,就可以实现了基本的const的效果了。

暂时不去深究了。以后有空再说。

转载请注明:在路上 » 【已解决】Android(Java)中的const变量定义出错:Syntax error on token "const", delete this token

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.193 seconds, using 22.12MB memory