java - Assign unique ID for every new Class (not instance!)
问题描述
I was wondering, whether it would be possible to assign a unique ID for every new class (not instance!).
Example of what I mean:
public class ChildObjectOne extends SuperClass {}
public class ChildObjectTwo extends SuperClass {}
public SuperClass {
private final int ID;
public SuperClass() {
this.ID = newID();
}
}
final ChildObjectOne childObjectOne = new ChildObjectOne();
final ChildObjectTwo childObjectTwo = new ChildObjectTwo();
System.out.println(childObjectOne.getID()); //prints 1
System.out.println(childObjectOne.getID()); //prints 2
childObjectOne = new ChildObjectOne();
childObjectTwo = new ChildObjectTwo();
System.out.println(childObjectOne.getID()); //prints 3
System.out.println(childObjectOne.getID()); //prints 4
What I want it to do instead is print 1 and 2 again. It should generate a new ID for every new class, but if I create a new instance of that class, I want the ID to stay the same.
I tried to achieve this using generics:
public SuperClass<T> {
private static int ID;
public SuperClass() {
this.ID = newID();
}
}
public class ChildObjectOne extends SuperClass<ChildObjectOne> {}
public class ChildObjectTwo extends SuperClass<ChildObjectTwo> {}
I was hoping, it would count passing a different T as a new class, but that didn't work. Instead the ID is the last one that was set.
How can I achieve this kind of ID system?
解决方案
Class::getName
Each class in Java already carries a unique identifier: the fully-qualified name of the class. No need for you to add an identifier.
Access the fully-qualified name by calling Class::getName
.
For a class:
String.class.getName()
"java.lang.String"
For an object (an instance), call Object::getClass
, and then Class::getName
.
customer.getClass().getName()
com.example.invoicing.Customer
推荐阅读
- python - 没有切片列表的 MergeSort
- javascript - 寻找循环解决方案的方形文本问题
- sql - 如何在 SQL 中对数组进行 string_agg?
- node.js - 在 Node 8.x 及更高版本中调试 Protractor 测试
- python - 两个排序的部分重叠的numpy数组之间的索引映射
- r - 计算多个因子变量中的出现次数
- regex - 使用正则表达式查找和替换 - 仅删除字母之间的双空格
- javascript - 我们可以说 String 是 Javascript 中的对象吗?
- javascript - 如何将外部网站链接到导入的 React src 图像?
- javascript - 如何在html中控制滑块速度