java常量和kotlin常量

  • java中使用final声明常量
  • kotlin中使用const val声明常量

常量在编译为字节码后会直接把调用常量的地方直接替换为常量值,示例如下:

public class ConstDemo {public static final String NAME = "Even";private static final int ID = 1001;static final int YEAR = 2024;public final int color = 255;public static int width = 100;public int height = 200;public static void main(String[] args) {System.out.println(NAME);System.out.println(NAME);System.out.println(ID);System.out.println(ID);System.out.println(YEAR);System.out.println(YEAR);ConstDemo demo = new ConstDemo();System.out.println(demo.color);System.out.println(demo.color);final int number = 9;System.out.println(number);System.out.println(number);System.out.println("--------------------------------");final int count;if (width > 100) {count = 1;} else {count = 2;}System.out.println(count);System.out.println(count);System.out.println(width);System.out.println(width);System.out.println(demo.height);System.out.println(demo.height);int weight = 99;System.out.println(weight);System.out.println(weight);}}

编译后得到class字节码,在IntelliJ中可以直接双击这个class字节码,它是自带反编译器,效果如下:

public class ConstDemo {public static final String NAME = "Even";private static final int ID = 1001;static final int YEAR = 2024;public final int color = 255;public static int width = 100;public int height = 200;public ConstDemo() {}public static void main(String[] args) {System.out.println("Even");System.out.println("Even");System.out.println(1001);System.out.println(1001);System.out.println(2024);System.out.println(2024);ConstDemo demo = new ConstDemo();PrintStream var10000 = System.out;Objects.requireNonNull(demo);var10000.println(255);var10000 = System.out;Objects.requireNonNull(demo);var10000.println(255);int number = true;System.out.println(9);System.out.println(9);System.out.println("--------------------------------");byte count;if (width > 100) {count = 1;} else {count = 2;}System.out.println(count);System.out.println(count);System.out.println(width);System.out.println(width);System.out.println(demo.height);System.out.println(demo.height);int weight = 99;System.out.println(weight);System.out.println(weight);}
}

如上代码,可以发现,只要是final修饰的变量在调用时直接被常量值替代了,有一个例外,就是在局部变量中声明的final int count;,它不是在声明时直接赋值的,而是经过一个if判断之后才赋值的,所以需要在运行时才能确定它的值是多少,所以在编译为字节码时调用该变量的地方没有被常量值替换,因为此时不知道它的值是多少。

另外也看到了一些有趣的地方,编译时编译器会有一些优化,比如int number = true;还能这样啊?没搞懂,它的final被去掉了,count中地final修饰符也被去掉了,而且类型变成了byte类型,编译器通过if中的判断得出值不是1就是2,用byte足已,所以改成了byte类型。

基于这个常量的特性,我们可以猜到,通过反射也是无法修改final类型的常量的,示例如下:

public class ConstDemo {public static final int age = 18;public static void main(String[] args) throws Exception {Field field = ConstDemo.class.getField("age");System.out.println("age = " + field.get(null));field.set(null, 30);System.out.println(age);}
}

运行结果如下:

age = 18
Exception in thread "main" java.lang.IllegalAccessException: Can not set static final int field ConstDemo.age to java.lang.Integerat java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:76)at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:80)at java.base/jdk.internal.reflect.UnsafeQualifiedStaticIntegerFieldAccessorImpl.set(UnsafeQualifiedStaticIntegerFieldAccessorImpl.java:77)at java.base/java.lang.reflect.Field.set(Field.java:799)at ConstDemo.main(ConstDemo.java:9)

从这里也可以看出,为什么常量在编译为class字节码之后,调用它的地方已经被常量值所替换,为什么常量的声明语句还保留了,因为还是有可能会被用到的,比如我们通过反射读取该常量的值,这是需要在运行时才能完成的,无法在编译阶段就直接使用常量值替代的。

再来看一个Demo:

public class ConstDemo {public final int age = 18;public static final ConstDemo demo = new ConstDemo();public static void main(String[] args) throws Exception {System.out.println(demo);System.out.println(demo);System.out.println(demo.age);System.out.println(demo.age);}
}

编译为字节码后,再反编译结果如下:

public class ConstDemo {public final int age = 18;public static final ConstDemo demo = new ConstDemo();public ConstDemo() {}public static void main(String[] args) throws Exception {System.out.println(demo);System.out.println(demo);PrintStream var10000 = System.out;Objects.requireNonNull(demo);var10000.println(18);var10000 = System.out;Objects.requireNonNull(demo);var10000.println(18);}
}

可以看到声明为非原始类型的final常量在编译为字节码时无法使用常量值代替,因为它是一个对象,而对象的内存地址得在运行时才能确定,所以这种不应该叫常量的,所以,kotlin在这方面就做的比较好,表示一个变量不可改变用val,表示一个常量用const val,分得更加清楚,示例如下:

const val NAME = "Even"class ConstDemo {val width = 100var height = 200companion object {const val ID = 1001@JvmStaticfun main(args: Array<String>) {println(NAME)println(NAME)println(ID)println(ID)val demo = ConstDemo()println(demo.width)println(demo.height)}}}

可以看到,声明常量的地方只能是顶级属性或者companion object中,要查看反编译,如果直接在IntelliJ中找到class文件然后双击会发现反编译不了,我们可以这样查看:工具 > Kotlin > 显示Kotlin字节码 > 反编译,结果如下:

public final class ConstDemo {private final int width = 100;private int height = 200;public static final int ID = 1001;public final int getWidth() {return this.width;}public final int getHeight() {return this.height;}public final void setHeight(int var1) {this.height = var1;}public static final void main(@NotNull String[] args) {Intrinsics.checkNotNullParameter(args, "args");String var2 = "Even";System.out.println(var2);var2 = "Even";System.out.println(var2);short var4 = 1001;System.out.println(var4);var4 = 1001;System.out.println(var4);ConstDemo demo = new ConstDemo();int var3 = demo.getWidth();System.out.println(var3);var3 = demo.getHeight();System.out.println(var3);}
}public final class ConstDemoKt {@NotNullpublic static final String NAME = "Even";
}

在Kotlin中,常量只能是8大原始类型,不能是对象类型的,如下代码在编译器就报错了:
在这里插入图片描述
声明常量有什么好处?这里我想到之前写的一篇文章:https://blog.csdn.net/android_cai_niao/article/details/113571171

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/441462.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Scrum敏捷研发管理全流程/scrum管理工具

Leangoo领歌是一款永久免费的专业的敏捷开发管理工具&#xff0c;提供端到端敏捷研发管理解决方案&#xff0c;涵盖敏捷需求管理、任务协同、进展跟踪、统计度量等。 Leangoo领歌上手快、实施成本低&#xff0c;可帮助企业快速落地敏捷&#xff0c;提质增效、缩短周期、加速创新…

华为---STP(二)---STP报文和STP端口状态

目录 1. STP报文简介 1.1 Configuration BPDU 1.2 TCN BPDU 2. STP交换机端口状态 2.1 STP交换机端口状态表 2.2 STP交换机端口状态迁移过程图 2.3 STP交换机端口状态变化举例说明 3 引起的STP网络拓扑改变的示例 3.1 根桥出现故障 3.2 有阻塞端口的交换机根端口所在…

数学知识第六期 中国剩余定理

前言 中国剩余定理也要学好的哈&#xff0c;共勉&#xff01;&#xff01;&#xff01; 一、中国剩余定理的介绍 中国剩余定理释义&#xff1a;又称“孙子定理”。1852年&#xff0c;英国来华传教士伟烈亚力将《孙子算经》中“物不知数”问题的解法传至欧洲。1874年&#xff…

springboot整合dubbo3 及其中遇到的坑

前言 之前以及了解过了springboot cloud 微服务的一系列框架,其中dubbo在3之前一直作为一款优秀的rpc框架存在(对标spring cloud中的feign组件),为此duboo3出以后,dubbo也逐渐变成了一个微服务整合平台,目前我进行学习的是个时候遇到很多坑dubbo x springboot 官方开发文档 环…

ElementUI组件:Button 按钮

button按钮 点击下载learnelementuispringboot项目源码 效果图 el-button.vue页面效果图 项目里el-button.vue代码 <script> export default {name: "el_button",// 注意这里的名称不能和 router inex.js里的name一样methods: {sendMsg() {// alert(1)xthi…

知识点积累系列(一)golang语言篇【持续更新】

云原生学习路线导航页&#xff08;持续更新中&#xff09; 本文是 知识点积累 系列文章的第一篇&#xff0c;记录golang语言相关的知识点 1.结构体的mapstructure是什么 mapstructure:"default" mapstructure是一个Go语言的库&#xff0c;用于将一个map中的值映射到…

[嵌入式系统-6]:龙芯1B 开发学习套件 -3-软件层次架构

目录 一、龙芯软件架构 1.1 通用软件架构 1.2 龙芯软件架构 1.3 龙芯各种应用程序 1.4 龙芯SOC芯片硬件&#xff1a;龙芯1B 1.5 PMON软件 1.6 龙芯IDE管辖的软件 &#xff08;1&#xff09;CPU Core驱动程序 &#xff08;2&#xff09;SOC芯片外设驱动程序 &#xff…

螺旋遍历二维数组【leetcode】

给定一个二维数组 array&#xff0c;请返回「螺旋遍历」该数组的结果。 螺旋遍历&#xff1a;从左上角开始&#xff0c;按照 向右、向下、向左、向上 的顺序 依次 提取元素&#xff0c;然后再进入内部一层重复相同的步骤&#xff0c;直到提取完所有元素。 示例 1&#xff1a; …

[docker] Docker容器服务更新与发现之consul

一、consul的相关知识 1.1 什么是注册与发现 服务注册与发现是微服务架构中不可或缺的重要组件。起初服务都是单节点的&#xff0c;不保障高可用性&#xff0c;也不考虑服务的压力承载&#xff0c;服务之间调用单纯的通过接口访问。直到后来出现了多个节点的分布式架构&#…

走迷宫-bfs

package Test;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;public class Main {static int N 110,hh 0,tt -1,n,m;static int[][] g new int[N][N]; //用来存储迷宫static int[][] d new int[N][N]; //用来存储d[i…

【送书福利-第三十期】《Java面试八股文:高频面试题与求职攻略一本通》

内容简介 本书将碎片化的Java面试八股文知识点系统化、结构化&#xff0c;精选了近200道经典高频的八股文面试题&#xff0c;整理了近20个经典高频的实战场景解决方案&#xff0c;准备了10多个面试简历实操技巧。每道面试题都标注了难度指数、考查频率、开发年限和匹配岗位等&…

c++之说_9_6|自定义类型 struct operator 重载运算符关键字

c中 struct 和 class 特性几乎一模一样 所以很多都是共有的特性 篇幅就很多了 c中 我觉得最牛皮的概念之一 就是 重载运算符 operator 关键字 这个东西 能将 我们的 运算符 &#xff08;-*/&#xff09; new delete 类型转换 写在类里面当成员函数 并制定 该类型变…