Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing package-private fields in classes shared across Eclipse projects

I have a model class (MVC pattern) that I'm using in two Eclipse projects.

One project, let's call it Producer, is capturing data from a stream and storing it to a database. The model class in question, say ObjectModel, is used to deserialize the stream for manipulation before serializing and storing in the db.

Another project, let's call it Consumer, is pulling in the data stored in the database and visualizing it on-screen. It uses the same model class to deserialize the stored data for use in the visualization application.

I planned to put ObjectModel into an Eclipse project to share its source across the Producer and Consumer projects. However, each application has classes currently in the same package that take advantage of the package-private access modifier to get and set fields in ObjectModel.

Is there any way I can share source across multiple Eclipse projects and still maintain package-private access with the shared source?

UPDATE: I was having trouble getting code shared across Eclipse projects, which is why I didn't just try this before posting. Finally got that part working, and wrote it up as another answer here.

like image 811
ericsoco Avatar asked Nov 03 '22 15:11

ericsoco


2 Answers

As long as the classes in the Producer and Consumer projects are declared in the same package as the ObjectModel, it should all just work.

However, you may want to rethink your design, and provide public accessor methods (getters and setters) in the ObjectModel.

like image 71
GreyBeardedGeek Avatar answered Nov 11 '22 08:11

GreyBeardedGeek


Look on @GreyBeardedGeek answer above:

As long as the classes in the Producer and Consumer projects are declared in the same package as the ObjectModel, it should all just work.

You are looking for the C++ friend in Java. In general, it can be symptom of wrong design. If your design is ok, then using "package-private access" is Java standard way for implementing friends. It will technically works if your classes are in different projects... If you think your design is ok, maybe you would like to consider using *Heper class. For example:

public class SomeClass {
 void foo(){...
 }
}

public class SomeClassHelper {
 private SomeClass someClass;
 public SomeClassHelper(SomeClass someClass){
  //you can do it better this with some DI Framework,
  //for illustration purpose
  this.someClass=someClass;
 }

 public SomeClassHelper(){
  //for illustration purpose only
  this.someClass=new SomeClass();
 }

 **public** void foo(){
    //this is punch line
    someClass.foo();
  }

}

You should place SomeClassHelper at the same package as SomeClass, but SomeClassHelper can be at different source folder or project.

like image 28
alexsmail Avatar answered Nov 11 '22 08:11

alexsmail