Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Java interface in another package be refactored from my code?

I'm using an (open-source) API in my Java project and referencing interfaces from it. One interface (Foo) is used extensively both in the API and in projects that use it. For my project, I'd like to use an interface which only exposes a subset of the methods that Foo does, such that Foo would inherit methods from my new interface (Bar). I don't want to change the interface of Foo at all; rather, I'd like to be able to write classes which implement Bar, and then manipulate those along with classes which implement Foo as if they are all Bar.

Since the API is in a different package, is there any way to accomplish this such that Bar is a superclass (interface) of all Foo?

like image 984
Henry Merriam Avatar asked Feb 23 '23 08:02

Henry Merriam


2 Answers

You're probably going to need to use an Aspect to make this happen. It looks like AspectJ has a @DeclareParents that might do what you want.

like image 35
Nick Veys Avatar answered Feb 25 '23 21:02

Nick Veys


I'd like to be able to write classes which implement Bar, and then manipulate those along with classes which implement Foo as if they are all Bar.

You can create an abstract Bar that implements Foo. You'll leave off the methods shared by the two and implement the methods that Bar does not share so they throw an exception like UnsupportedOperationException.

But you can't manipulate Foo as if it were Bar; it's the other way 'round. You can't satisfy the Liskov Substitution Principle the way you're proposing.

like image 112
duffymo Avatar answered Feb 25 '23 22:02

duffymo