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
The ReplaceExpression is an overloaded function that return different subclasses.

 // Expression is abstract class, A and B 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(1);
Expression e2 = ReplaceExpression("a");

    
    public Expression ReplaceExpression(int i)
    {
    Return new A();
    }
    
    public Expression ReplaceExpression(String s)
    {
    Return new B();
    }

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

if (ReplaceExpression(x).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