mercredi 23 juin 2021

How to dynamically create an object for an abstract class without casting?

I have a abstract class in JAVA and few subclasses. I have a function that returns an instance of one of these subclasses. I don't want to check with few if...else to create an object based on the return type. need to do it dynamically at run time. this solution didn't help me

// Expression is abstract class, A is subclass\
    // this return me null because i did not make a new object for e1, I know a subclass of Expression
    Expression e1 = ReplaceExpression();

I can do it like this but i need cleaner solution:

if (ReplaceExpression().getClass().getSimpleName() == "A")
Expression e1 = new A();

So my question is: is there anyway I can instantiate a new subclass for my abstract class without hardcoding or casting? something like dynamically or reflection





Aucun commentaire:

Enregistrer un commentaire