mercredi 4 septembre 2019

Invoke Method of Subclass with Matching Regex

I am trying to call a method, convert(), based upon the return value matching the class' regex() method, both of which are defined in the below base class:

public abstract class BaseClass {
    public abstract BaseClass convert(String value);
    public abstract String regex();
}

I also have several subclasses that have implementations of those methods. I want to be able to do something like the below method (which will reside in BaseClass):

public static BaseClass parseNew (String value) {

    // I use a switch statement to convey the idea of what I want to
    // do, not for functionallity. Any non-constant cases raise
    // compiler errors.
    switch (value) {
        case new Subclass1().regex():
            return new Subclass1().convert(value);
        case new Subclass1().regex():
            return new Subclass1().convert(value);
        // Repeat for all known and possibly unknown subclasses
    }
}

I was thinking about using reflection, but I am very afluent in it. How would I get this functionality using reflection or some other concept?





Aucun commentaire:

Enregistrer un commentaire