I have this monolithic Java-Application that I want to port to newer techniques and I want to apply Scala wherever it makes sense.
Now I translated a rather huge java-singleton class implementation to a Scala object.
In another class I used to do this (JAVA):
public class MyOtherClass
{
protected MyClass myClass;
public MyOtherClass()
{
myClass = MyClass.getInstance();
}
}
Now I'd like to do the following:
public class MyOtherClass
{
protected MySCALAClass myClass;
public MyOtherClass()
{
myClass = MySCALAClass$.MODULE$;
}
}
But this doesn't work. It says:
Required MyScalaClass, Found MyScalaClass$
I also tried to create a small function
def getInstance() = this
but of course this yields the same problem.
Any ideas? I have searched this topic and I see how it is not a problem if you just want to call the methods of the object, but I would need to rewrite many, many calls to the "myClass"-object to even test this.
edit: I'm fully aware that I could rename every call to "myClass" to "MySCALAClass", but that is no real fix, just a workaround and it is tedious for a big project.
I think #neuronaut 's comment is correct.
See following questions:
Scala object MODULE$
Singletons as Synthetic classes in Scala?
The singleton class (MySCALAClass$ in your case) is not a subclass of the original class (MySCALAClass) and so the singleton object (MySCALAClass$.MODULE$) is not an instance of it either.
Related
Nowadays we are on writing some core application that is all other application will be relying on. Without further due let me explain the logic with some codes,
We used to have a single java file that was 1000+ lines long and each application was having it as class inside, so when there was a change, each application had to edit the java file inside of it or simply fix one and copy to all. This is hard to implement as much as it is hard to maintain. Then we end-up with creating this as a separate application that is divided to smaller part, which is easy to maintain and also a core maybe a dependency to other application so we fix in one place and all other code applications are fixed too.
I've been thinking for a some great structure for this for a while want to use a builder patter for this as below
TheCore theCore = new TheCore().Builder()
.setSomething("params")
.setSomethingElse(true)
.build();
The problem arises now. Like so, I initialized the object but now I'm having access to that objects public class only. This application actually will have many small classes that has public functions that I don't want them to be static methods that can be called everytime. Instead I want those methods to be called only if TheCore class is initilized like;
// doSomething() will be from another class
theCore.doSomething()
There are some ideas I produced like
someOtherClass.doSomething(theCore)
which is injecting the main object as a parameter but still someOtherClass needs to be initialized or even a static method which doesn't make me feel comfortable and right way to that.
Actually I do not care if initializing TheCore would bring me a super object that includes all other classes inside initialized and ready to be accessed after I initialized TheCore. All I want in this structure to have a maintainable separate app and methods avaiable if only the main object which is TheCore is this circumstances is initialized.
What is to right way to achive it? I see that Java does not allow extending multiple classes even it if does, I'm not sure it that is right way...
Thanks.
After spending significant amount of time of thought I ended up that
// doSomething() will be from another class
theCore.doSomething()
is not suitable since many java classes could possibly have identical method names. So...
// doSomething() will be from another class
theCore.someOtherClass.doSomething()
would be a better approach.
To make it easier to understand I'll have to follow a complex path to explain it which is starting from the package classes first.
Think that I have a package named Tools and a class inside SomeFancyTool
main
└─java
└─com
└─<domainName>
├─Tools
| └─SomeFancyTool.java
└─TheCore.java
Now this SomeFancyTool.java must have a default access level which is actually package level access, because I don't want this classes to be accessed directly;
SomeFancyTool.java
package com.<domainName>.Tools
class SomeFancyTool{
public String someStringMethod(){
return "Some string!";
}
public int someIntMethod(){
return 123;
}
public boolean someBooleanMethod(){
return true;
}
}
So now we have the SomeFancyTool.java class but TheCore.java cannot access it since it is accesible through its Tools package only. At this point I think of an Initializer class that is gonna be in the same package, initialize these private classes and return them with a function when called. So initiliazer class would look like this;
ToolsInitializer.java
package com.<domainName>.Tools
public class ToolsInitializer{
private SomeFancyTool someFancyTool = new SomeFancyTool();
public SomeFancyTool getSomeFancyTool(){
return someFancyTool;
}
}
Since ToolsInitializer.java can initialize all functional private classes inside in Tools package and also can return them as objects to outside of the package scope, still we are not able to use these methods as we cannot import com.<domainName>.SomeFancyTool from TheCore.java because it is package wide accessible. I think here we can benefit from implementation of the java interface. A class that is not functional alone, so no problem even if it is accessed since it's methods will be nothing but declarations.
At this point I'll rename SomeFancyTool.java to SomeFancyToolImplementation.java which it will be implementing the interface and call SomeFancyTool.java to the interface itself.
SomeFancyTool.java (now as an interface)
package com.<domainName>.Tools
public interface SomeFancyTool{
public String someStringMethod();
public int someIntMethod();
public boolean someBooleanMethod();
}
and lets rename prior SomeFancyTool.java and implement the interface
SomeFancyToolImplementation.java (renamed)
package com.<domainName>.Tools
class SomeFancyToolImplementation implements SomeFancyTool{
#override
public String someStringMethod(){
return "Some string!";
}
#override
public int someIntMethod(){
return 123;
}
#override
public boolean someBooleanMethod(){
return true;
}
}
Now our structure has become like this with the final edits;
main
└─java
└─com
└─<domainName>
├─Tools
| ├─SomeFancyTool.java
| ├─SomeFancyToolImplementation.java
| └─ToolsInitializer.java
└─TheCore.java
Finally we can use our TheCore.java class to call all initializer classes with their methods to receive all these private classes inside as an object. This will allow external apps to call and initialize TheCore first to be able to access other methods.
TheCore.java
public class TheCore{
private SomeFancyToolImplementation someFancyTool;
public static class Builder{
private SomeFancyToolImplementation someFancyTool;
public Builder(){
ToolsInitializer toolsInitializer = new ToolsInitializer();
someFancyTool = toolsInitializer.getSomeFancyTool();
}
public Builder setSomeValues(){
//some values that is needed.
return this;
}
public Builder setSomeMoreValues(){
//some values that is needed.
return this;
}
public TheCore build(){
TheCore theCore = new TheCore();
theCore.someFancyTool = someFancyTool;
return theCore;
}
}
}
All Done and it is ready to use. Now the functional package classes and its methods that it relying on if TheCore is initialized or not, cannot be accessed with out TheCore. And simple usage of this Library from a 3rd Party app would simply be;
3rd Party App
TheCore theCore = new TheCore.Builder()
.setSomeValues("Some Values")
.setMoreSomeValues("Some More Values")
.build();
theCore.someFancyTool.someStringMethod();
Note: Note that a the ToolsInitializer.java is still accessible and could be used the get private method without first calling TheCore but we can always set a checker inside getSomeFancyTool() method to throw error if some prerequisites are not satisfied.
I do not still know if this is a functional structural pattern to use or its just some hard thoughts of mine. And don't know if some pattern is already exist that I just could not see yet but this is the solution I end up with.
I've got interface 'FileFactory' with 'produce' method.
This interface is implemented by two classes: 'SingleFileFactory' and 'MultipleFileFactory'.
Both of these classes have the same code structure but returning different injected object.
IntelliJ prints infirmation, that code in both classes is duplicated.
I can't paste original code, so it's an example
Example:
public class SingleFileFactory {
#Inject
private FiirstSingleFile firstSingleFile;
#Inject
private SecondSingleFile secondSingleFile;
public File produce() {
if(something)
return firstSingleFile;
else
return secondSingleFile;
}
}
Class 'MultipleFileFactory' has the same logical but different injected objects.
I wanted to separate code into multiple classes, because in my opinion each can return specific object in the result.
Do you know how to avoid such as duplication - should I stretch it and pack into one class with a lot of injects and if expressions?
Maybe you have better solution for this problem.
My project is heavily using dependency injection, and I'm being very careful to avoid service locator antipattern. All objects are structured using constructor injection that allow easily identifiable list of dependencies. Now I'm building an object, and it has a special "constant" instance, which is basically static/singleton (consider example of something like Integer.MinValue). So my initial reflex was to create a static field with a static "getter" method, which would create the instance of the object if it wasn't previously created. The object itself has dependencies however, so I'm confused on what's the best practice for instantiating this "special instance". I'm looking for recommendations on how to best structure code in this scenario, ideally without having to call upon the container for resolution of dependencies. Some code:
public class PressureUnit extends DataUnit {
private static PressureUnit standardAtmosphere;
public static PressureUnit StandardAtmosphere() {
if(standardAtmosphere == null){
standardAtmosphere = new PressureUnit(1013.25); // this line is what is bothering me as I need to resolve other dependencies (have to use new as it's a static method and can't be injected like everywhere else)
}
return standardAtmosphere;
}
#AssistedInject
public PressureUnit(ITimeProvider timeProvider, IUnitProvider unitProvider, #Assisted double value) {
this(timeProvider, unitProvider, value, PressureUnits.hPa);
}
...
}
I really don't see any problem in your code since you are not newing up dependencies here and there, now with that being said i can give some suggestions:
If you specifically want the container to call an existing static factory method, you can use StaticFactoryExtension.
Why don't you use a factory.
Consider refactoring you design and removing the static method if possible.
I guess this is a bad pattern, whats the best approach to fix it?
I mean I would like everybody using a constructor with 2 arguments,but I need to leave default constructor because its implementing a listener which classloads it without args. I would like to hide default constructor to anyone else but the listener handler which uses it, and make the other the unique point to instantiate.
Is there any kind of annotation? any privacy modifier for certain classes (system caller one is not in the same package)?
This seems fine to me. You would do the same thing if you want to instantiate a class differently during unit testing.
Oh, I see you need a constructor that has more access than protected but less than public. Unfortunately that's not possible.
You could put both your class MyClass and the listener MyListener that needs to use the empty constructor in the same package. Then, set the access of the empty constructor to package-level:
package com.stackoverflow.foo;
public class MyClass {
MyClass () { // package-private (no explicit access modifier)
}
public MyClass(int a, int b) { // public
}
}
package com.stackoverflow.foo;
public class MyListener {
private MyClass ref = new MyClass(); // MyListener is on the same package as MyClass, so this is valid
}
This way, you ensure that only classes that are on the same package as MyClass can use the default constructor.
I have a library project which contains an abstract class, let's say ClassA. In the project that uses that library project, I have ClassB that extends ClassA.
Now here's my problem. In the library project I want to use an instance of the implemented ClassB, but I have no idea how to retrieve that instance. Is there any pattern or other ideas for this?
Here's a simple diagram of the situation.
Edit
The reason I'm asking is that I'm creating multiple applications, which only have different methods in ClassB. Therefore I'm creating a library that all of these applications can use, only having to extend ClassA. These applications are separate projects, using the library.
What you're looking for is something like the Abstract Factory pattern. The application code (the code that calls into the library) would, at some point, need to pass in a Factory class that would be used by the library to create instances of ClassA objects. In your case, the Factory class would generate instances of ClassB.
Depending on the design and functionality of the classes, it's likely that ClassA should be redesigned as an interface, or at least as an abstract class, as part of this refactoring.
EDIT:
Here's an untested pseudo example:
This code would be in the library
class INeedAFactory {
public Interface MyFactory {
public ClassA makeClassAInstance();
}
private MyFactory m_factory;
public registerFactory(MyFactory factory) {
m_factory = factory;
}
private ClassA makeClassAInstance() {
// m_factory had better not be null!
return m_factory.makeClassAInstance();
}
private void ClassAConsumer() {
ClassA classA = makeClassAInstance();
// ... etc. ...
}
}
This code would be in the application:
class LibraryPatron {
class MakeClassB implements INeedAFactory.MyFactory {
public ClassA makeClassAInstance() {
return new ClassB();
}
}
public LibraryPatron() {
INeedAFactory libraryObject = new INeedAFactory();
libraryObject.registerFactory(new MakeClassB());
// ... etc...
}
}
If your library needs to use ClassB, then ClassB should be part of your library. Your library shouldn't need to know about classes in projects which use it.
If your library just needs a ClassA, and you've got a ClassB, you can cast your object to a ClassA before you pass it in, like this:
ClassB b = new ClassB();
ClassA a = (ClassA)b;
// pass a into your library
Move class B into the same library as class A. Your project already depends on the library so it will still be able to reference class B but class B will also now be available to other classes within the library.
It isn't really clear, but as I understand it if you want to get an instance of the ClassB you just need to do a new ClassB()...
So you're writing an abstract class and you want it to be able to get a hold of all objects of unknown sub-classes of that class? It sounds to me like you're wanting an Aspect-Oriented management like AspectJ or PicoContainer.
I feel sick when I write this, because your design is flawed, but you asked how you would do it....so here it goes:
Class<?> bClass = Thread.currentThread().getContextClassLoader().loadClass("com.foo.ClassB");
Then you can do something like:
if (object.getClass() == bClass) { ... }
I would seriously recommend coming up with a better solution however. Try writing your code in one project then re-factor out common things that can make up your "library".