首页 > 解决方案 > 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?

标签: javaarchitecturegame-engine

解决方案


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


推荐阅读