简体   繁体   中英

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 )?

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");
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM