开发者

Adding methods/modifying classes of a jar

开发者 https://www.devze.com 2023-04-10 00:27 出处:网络
Very silly question, I am doing a project and I can\'t think about any workaround I have implemented new functions in an open jar (let\'s call it converter), I want to modify one of these methods: Exc

Very silly question, I am doing a project and I can't think about any workaround I have implemented new functions in an open jar (let's call it converter), I want to modify one of these methods: ExchangeToEuro, ExchangeToDollar, CheckCurrency.

My question is: Are there any mechanism for which I can add functionality (modifying of of these methods or even adding met开发者_开发知识库hods to this class) to the class without modifying the jar (without modifying the classes present in the jar)?

I thought about a class decorator, but that wouldn't work as I would need to modify the jar itself.


You can extend classes within Converter.jar, as long as they are not final, and override the methods contained within them, as long as they are visible and not final as well. Say Converter.jar had a class like this:

public class ExchangeToDollar {
    public BigDecimal exchangeEuroToDollar(final BigDecimal euroValue) {
        ...method implementation....
    }
}

You could extend and override like this:

public class MyClass extends ExchangeToDollar {
    @Override
    public BigDecimal exchangeEuroToDollar(final BigDecimal euroValue) {
        ...your implementation....
    }
}

The MyClass.exchangeEuroToDollar(BigDecimal) method overrides the exchangeEuroToDollar(BigDecimal) implementation that's contained within the ExchangeToDollar class in Converter.jar, meaning that when you call the method on an instance of MyClass, your implementation will be executed.

The downside of this type of implementation is that any code that you do not have control over that uses ExchangeToDollar will not be able to use your overridden implementation, unless you can pass a MyClass instance in instead.


It's not entirely clear what kind of modifications you need to make, but if you need to modify class methods themselves, you options are limited to things like AspectJ or less-clean forms of byte-code manipulation using tools like BCEL or ASM.

You could conceivably create the additional functionality in a different JVM language like Groovy/etc., compile to .class files, and use those.

You may need to provide more and/or less-contradictory info, though.


Extend the classes, add what new functionality is required, and override that which should change.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号