Solved Get a value from specific class extending a base

Discussion in 'Spigot Plugin Development' started by danablend, May 16, 2016.

  1. Say I have like 50 different classes extending 1 base-class, they all have some abstract variables. How would I create 1 method where I can specify a class I want a variable from, and get that variable. For example if I had 3 classes extending Person, and they had abstract name variables with the names "John, Josh and Jennica" How would I have 1 method that would let me specify a class to get a variable from? So like getName(John) would give me the name of John, getName(Jennica) the name of jennica etc...? I would like this possible without having instances of every single class I need to use getters for?
  2. Object getValue(BaseClass obj){
    return obj.theValue;
    OMG why dont you just access the abstract member value directly?
  3. Just create a field for the value in the abstract class. Or if you really, really can't, create an abstract method in the abstract class.
  4. I decided to make a static collection of all instances and add each instance of all the extending classes on startup. Might not be best solution but thats the best solution i could come up with. Also works great because its static. Downside might be missing instances or something similar.
  5. you shouldn't do this in the base class as per single responsibility principle :p. Secondly, you might want to use Map instead of a Collection, which maps the implementation type to the instance.

    Depending on what you're actually writing, you could also try mixins (enum implementing interface, giving each enum variable it's own impl)