-4

I want to create a situation where a group of classes (inherited from the same base class) all have a different unique ID. The ID belongs to the class, not to it's instances. The ID should not be sensitive to code changes (so runtime computation of the ID based on some properties is out of the question). Also, I need it to be not sensitive to classes adition, meaning, that once a class got an ID, it will be the same ID even if I move the class , change it's name, or the using code Also, I need it to be programmer proof, so the ID will be auto-generated (by eclipse) and if accidentally is used twice - I will get an error. If possible I want to connect the ID to an Enum that will have a unique value for each possible ID, but this a secondary goal.

Any ideas?

Yoav R.
  • 531
  • 1
  • 3
  • 15
  • you can manually add an ID attribute with hardcoded UUID value for each class. It would be more useful if you could explain why you are doing this. What's the purpose of this? and what have you tried till now? – gagan singh Jun 18 '18 at 20:43

1 Answers1

0

You'd have to create a cache in the base class and a generation method:

public class Base {
    private static final Set<Integer> GENERATED_IDS = new HashSet<>();

    protected static int generateId(Class<? extends Base> subClass){
        final int id = subClass.getName().hashCode();
        if(GENERATED_IDS.contains(id)){
            throw new InstantiationError("id '" + id+ "' already used");
        }
        GENERATED_IDS.add(id);
        return id;
    }
}

I used here a simple getName().hashCode(). Which will be unique for every class you'll create. (No class can be named the same and be placed inside the same package)

public class Sub extends Base {
    public static final int ID = Base.generateId(Sub.class);
}

So you'll have a nice distribution of ids, which are just in fact the hashCodes of the Class objects of the subClasses.

Note: The hashCode still can vary, depending on the default charset

Lino
  • 19,604
  • 6
  • 47
  • 65
  • This is not relevant for me(I edited the question). I want this ID to be immune to code changes like renaming or class moving(I cant have this ID changing, because external project is dependent on it) – Yoav R. Jun 18 '18 at 20:31
  • @YoavR. then I am sorry, but this is just not possible. You might want to consider to just not rely on the generation of that ID but just hardcode it. Think about it like java itself does. They don't move classes around and rename them just because the like it. They keep them where they created them and live with the consequences. If you really need to care about these things, then you have to think about what exactly you're doing in your Project. – Lino Jun 18 '18 at 20:45