devoured elysium
devoured elysium

Reputation: 105037

How to add a method to a class on the fly? (not reflection related)

Is it possible to achieve something like this in Java? My idea was to add a method to a class using annonymous classes but this doesn't seem to work.

public class Abc {
    private ErrorsTable expectedErrorsTable = new ErrorsTable() {
        public ErrorsTable addError(String error) {
            this.add(error); //ErrorsTable is just a disguised ArrayList
            return this;
        }
    };

    ...

    public void someMethod() {
        expectederrorsTable.adError("abc");
    }
}

It is by no means a mistery why this doesn't work. The expectedErrorsTable is of type ErrorsTable so the compiler has no way of knowing that actually there lies an extended implementation equipped with addError(String).

What other simple ways of achieving the same effect could be used (other than creating a new file with a new class extending ErrorsTable)?

Upvotes: 0

Views: 340

Answers (1)

BalusC
BalusC

Reputation: 1108632

Define it as an inner class which extends the desired class and then declare against it instead.

public class Abc {

    private class ExpectedErrorsTable extends ErrorsTable {
        public ErrorsTable addError(String error) {
            this.add(error);
            return this;
        }
    }

    private ExpectedErrorsTable expectedErrorsTable = new ExpectedErrorsTable();

    public void someMethod() {
        expectedErrorsTable.addError("abc");
    }

}

Upvotes: 1

Related Questions