All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.kiryu1223.expressionTree.expressions.NewExpression Maven / Gradle / Ivy

There is a newer version: 1.4.5
Show newest version
package io.github.kiryu1223.expressionTree.expressions;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class NewExpression extends Expression
{
    private final Class type;
    private final List> typeArgs;
    private final Constructor constructor;
    private final List constructorArgs;
    private final BlockExpression classBody;

    public NewExpression(Class type, List> typeArgs, Constructor constructor, List constructorArgs, BlockExpression classBody)
    {
        this.type = type;
        this.typeArgs = typeArgs;
        this.constructor = constructor;
        this.constructorArgs = constructorArgs;
        this.classBody = classBody;
    }

    public Class getType()
    {
        return type;
    }

    public List> getTypeArgs()
    {
        return typeArgs;
    }

    public List getConstructorArgs()
    {
        return constructorArgs;
    }

    public BlockExpression getClassBody()
    {
        return classBody;
    }

    @Override
    public Kind getKind()
    {
        return Kind.New;
    }

    @Override
    public Object getValue()
    {
        try
        {
            List values = new ArrayList<>();
            for (Expression constructorArg : constructorArgs)
            {
                values.add(constructorArg.getValue());
            }
            Object[] array = values.toArray();
            return constructor.newInstance(array);
        }
        catch (InstantiationException | IllegalAccessException | InvocationTargetException e)
        {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String toString()
    {
        StringBuilder sb = new StringBuilder();
        sb.append("new ")
                .append(type.isAnonymousClass() ?
                        type.getSuperclass().getSimpleName() :
                        type.getSimpleName())
                .append("(");
        for (Expression constructorArg : constructorArgs)
        {
            sb.append(constructorArg).append(",");
        }
        if (sb.charAt(sb.length() - 1) == ',')
        {
            sb.deleteCharAt(sb.length() - 1);
        }
        sb.append(")");
        if (classBody != null)
        {
            sb.append(classBody);
        }
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        NewExpression that = (NewExpression) obj;
        return type.equals(that.type) && constructorArgs.equals(that.constructorArgs)
                && classBody.equals(that.classBody);
    }
}