【问题】
在Android中想要定义一个const字符串,结果出错:
Syntax error on token "const", delete this token |
【解决过程】
1.搜了点资料,也没有说清楚的。
2.后来参考了这个,说的比较清楚:
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 intointVal
, and extracts a reference from the classfile string constant table forstrVal
. 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 accessingintVal
will use the integer value 42 directly, and accesses tostrVal
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