How to call a singleton method from a Java POJO? - java

I wondered if it would be possible to call from a POJO a singleton bean's method through its interface. Maybe this idea is wrong or the architecture...but this is what I would like to accomplish if it is possible, because this is the architecture of the project.
I notice that when I call getInstance() (the method from the singleton's interface) from the POJO, there is an error occuring, telling me that the method has to be static, but if I make the method static, then I have to write the implementation in the interface and I can't get the singleton instance.

Your current approach with the interface is flawed. By default, all methods in an interface (up until Java 8) are static, and are implemented by instance methods in the implementing class.
This means, this is not an option. After all, you'll need to run the method to create an instance, meaning, you don't have an instance yet, so you have no instance to call it on.
Putting the same static method in an abstract class you extend, is also not a solution: a super class should never be aware of it's subclasses. If it is a static method (which it needs to be), you need to keep it in the class itself: a static method in an abstract class can (through an anonymous implementation of the abstract class) return an instance of the abstract class, but this is not the same as an instance of the subclass, which is what you are looking for.
In order to use this method for the subclass, you will need to inherit it from the super class. But, it will still return an instance of the super class. You'll need to overwrite the method in the subclass by the correct one, so the best solution is to add it straight in your Singleton class.

You are not allowed to have static methods in your interfaces (at least not until Java 8). Something like this is not allowed:
MyInterface var = new MyImplementingClass();
var.staticMethod();
Just remove the interface and do your static method call against the class where the static method resides.
Search a bit for the singleton pattern - the 'standard' way to do this involves classes and not interfaces, so rethink your design.

The idea seems to be wrong. A static method is always at a class level and hence you can never declare a method as static in a Java interface(you can do this in Java 8). However, this seems like the wrong design. If you really want to do something like this -
1)Make the Interface an abstract class.
2)Create a static method called getInstance();
3)Extend the abstract class in your POJO singleton class.
Hope this helps!!

Related

Is putting static methods in interfaces a good practice?

Let's say I have a method getAverageDifficulty in my class Difficulty that goes like this:
public static Float getAverageDifficulty (List<Difficulty> difficultyList) {
...
return average;
}
My method obviously needs to be static, since it makes no sense requiring an instance of Difficulty. Now let's say I'm using an interface IDifficulty so I can change my implementation later. Obviously, I do want my getAverageDifficulty method to be available from IDifficulty, and, as I can't declare a static method abstract, the obvious option is to put getAverageDifficulty directly in my interface. My question is: am I making a mistake by putting that static method in my interface, which contains other Difficulty methods waiting to be implemented? Should I not mix static and "normal" interface abstract methods? Should I create DifficultyHelper class and put my method there?
Ultimately, this is a matter of style. However, if the only purpose of the helper class is to hold this method (and maybe a few similar ones), then you will be saving yourself one class definition by placing them in the interface:
As of Java 8, the restriction that interfaces cannot contain static methods was eliminated, so there is typically little reason to provide a noninstantiable companion class for an interface [Effective Java, 3rd edition].
Static methods in interfaces are similar to the default methods except that we cannot override these methods in the classes that implements these interfaces.so in my opinion its not not necessary to write static methods in interfaces until you want to prevent overriding.

java singleton class vs final class

Can somebody, please explain me clearly on java singleton design pattern class vs java final class.
Can we use a final class instead of using a singleton class?
For a final class we can create the instance of the class and use the methods in that, but not overriding properties, if the methods are static in the final class, then we can just call the methods like ClassName.getMethod, why should we go for singleton instead of final class?
A final class is one which cannot be extended. You can have any number of instances in a final class. The best example of a final class is String. Singleton is a single instance of a class. So both are not exactly same, however you can make your singleton class final to restrict someone from extending it.
You can't extend a final class and there is only single instance for a singleton class. So inheritance concept is not applicable for the final class. But you can create any number of instances in final class but you can't in Singleton.
i.e, final class is immutable class, can create more than one instance but where as Singleton class has only single instance.
A singleton is a class with a single instance for all the life of your program. But a final class, you can have multiple instances of it. The thing is that you cannot inherit from a final class, but nothing stops you to have a lot of instances of it.
A singleton class is usually tied to the ClassLoader. Basically, you should have one per JVM. A final class is something you can't inherit from, but just because it's final it doesn't mean you can't have multiple instances of it (per JVM).
Notice that, when I say per JVM I'm talking about, for instance, a .class file in a .war file deployed once; if the same Web application is deployed multiple times, each one gets its own singleton.
I think your question is more about static versus singleton. Being a final class is not relevant in this context since you cannot override a static method (you can of course define the same signature static method in the extension but this would be irrelevant because the biding will still be "static" in the sense that calling SuperClass.getMethod will always call the definition from SuperClass). This is a classic question and I am sure you can find it answered elsewhere. However, just to give you a short answer, I would say that using a singleton allows you to implement interfaces and pass around your singleton object like any other object.
Maybe I can explain, to whomever gave me -1, what I meant (I thought it was clear enough). The original question is about singleton vs final. But when he explains, he states clearly that he is going to use static methods. He doesn’t realize then that what makes the methods unique in the sense that they belong to a single class is the fact that they are static, and so are class methods instead of instance methods. Being final has no effect: the user can instantiate as many as he wants, it only prevents him from extending the class, which did not seem to me to be the true concern of who asked the question.
On the other hand, he clearly states that he will use static methods on his final class. This seems then to indicate he wants to make it a singleton by using static methods: this is a classic way of doing it, and the question of using static methods versus singleton has been asked before. See for instance Why use a singleton instead of static methods? or Difference between static class and singleton pattern?
When I then write about overriding a static method, I try to explain that static method are not really overridden in the sense that they are not involved in dynamic binding. To give an example, if you have class A with static method foo() and then class B extends class A and redefines static foo(), that’s OK. But calling foo() on an object obj will call the static method belonging to the type of obj, even if you assign it a different object at runtime (this is what I call static binding). In other words, if you declare “A obj = new B()” and call obj.foo() it will still call A.foo()
I don’t know if that explanation helps, I wish whoever gave me -1 explained why.

Overriding an instance method with static ones

I have a class that will be subclassed. All subclasses must contain a static method with the same signature, but differnt for each one.
I would like to have an abstract instance method in the superclass that subclasses will override, but it seems mot possible in Java, I wonder why.
A silly example:
Image{
abstract String getExtension();...
RGBImage extends Image{
static String getExtension(){return "RGB"};..
PNGImage extends Image{
static String getExtension(){return "PNG"};...
Have a look at this explanation. You could use the Builder pattern for your purpose.
As others have said, Java does not support overriding or abstract for static methods. However, I don't really understand what you would achieve with an "abstract" static method anyway.
The normal use of an abstract method is to force every subclass to implement a method with the same signature. But why would it even it matter for a static (hence non-polymorphic) method? If you forget to provide the method for one of the subclasses, EITHER it doesn't matter because you don't call it, OR it does matter but you'll get a compilation error at the point you try to call the missing method.
The only use-case I can think of where it might matter is if you are calling the method reflectively in a pseudo-polymorphic way. But if you are doing that you'd be better off using real polymorphism and instance methods.
I don't do much Java, but (using C++ logic) you could make the base class implementation a dummy implementation that cannot be executed.
static void DoStuff(arg_type arg)
{
std::cerr << "Method DoStuff() must be overriden\n";
::abort();
}
That isn't as good as an abstract method, but it will achieve some of the same results.
Unfortunately, this is not possible in Java. You have to make them instance methods to be able to define as being abstract.
It's not possible to override static methods as they pertain to a class, not an instance.
Furthermore, an instance method cannot be made static in the sub-classes as you suggest in your example.
Can you provide more information as to why all the subclasses need to have the same static method?
You want to override instance method with static method ? That makes no sense. Static methods are not polymorphic. How would you like to call it? It is impossible in Java to enforce class to have a static method with given signature.
as others have said, static is not polymorphic... it means it is the same for the class, not specific to an instance. i am not sure what you would accomplish by using a static method... but you could have have your extended method implementation return a static value:
public String getExtension() {
return STATIC_CONSTANT;
}
I guess it depends on what you are trying to accomplish with the static method. From your post: "Let me say, everything works OK implemnting a instance getExtension() method in each subclass. But the point is that the method is in fact static in the subclass, has no dependence on the instance. I know I can't do that, I only saying it seems no so strange idea to me."
The problem is you are asking for polymorphic behavior (a change in the behavior of a method for each subclass) from something that defines behavior for the class, not the instance. By definition, static cannot be polymorphic. I hope this helps you with your understanding here of why this is not possible.
The reason I want to have the abstract method declared in the superclass is because the class has to do some extra work with the result of the abstract method.
Lets put it simple even the example has no sense:
Image{
abstract String getExtension();
int process(){
return getExtension().length
}
The algorithm in process() is common for all subclasses XXXImage of Image, so its right place is the superclass.
Let me say, everything works OK implemnting a instance getExtension() method in each subclass. But the point is that the method is in fact static in the subclass, has no dependence on the instance.
I know I can't do that, I only saying it seems no so strange idea to me.
Yes thaks, this is what I'm doing, retun a static constat. In may case it returns the class object of a inner enum that lists the name of sections of a given file format: the file format of the subclass.
But you put it very clear in your example:
public String getExtension() {
return STATIC_CONSTANT;
}
I was expecting to be able to put "static" before String...

why we should not use static and abstract for a single method?

why we should not use static and abstract for a single method?
the static keyword is defined so that a method can be called by a class name rather then an object. that means the method has to have some sort of definition. but abstract means you do not have any details about what the method does, it is as it says **Abstract**. When you inherit or extend a class you can then define the method.
Think of an interface.
If you are asking about having a static method inside of an abstract class, that is a different story. An abstract class is essentially as mentioned an interface and contains just a template of say functions that you must later on implement by inheriting / extending the class. Once you extend that class the static method does not come along with it (that is by default unless the access modifier is public / protected).
A static method is not inherited. Therefore, making it abstract is a nonsense.
The abstract keyword means that child classes must override the method - this is (one of the ways) Java supports polymorphism. If you want to make it so that subclasses cannot override the method you mark it final. So it would be impossible to have an "abstract final" method since they are the exact opposite of each other.
the static keyword implies final as well - all static method are also final. Thus it is impossible to have a method that is both static and abstract since you would be able to make a method that is abstract and final.
The reason for static being final is that it is bound to the class instead of the instance. That means that the compiler looks it up at compile time rather than runtime to determine which method to call. The reason what it is like that? Arbitrary decision that the designers of Java made - they could have allowed static method to be overridden but decided not to. I don't have any particular insight as to why the chose one over the other unfortunately.
As others have said, static+abstract is nonsense in Java. But there have been (rare) occasions where I've wished I could do just that.
The result I was looking for was basically to say that... "all concrete classes that extent this abstract class (or implement this interface) must provide a static method with this signature." This capability would allow these classes to provide meta-information about themselves.
Normally I have ended up with an instance method in these cases. If you stipulate that concrete implementations must support the default (no-arg) constructior, you can do...
MyInterface obj = MyClassThatImplementsMyInterface.newInstance();
obj.invokeTheMethodIWishWasBothStaticAndAbstract();

Uninstantiated Anonymous Classes in Java

It's been about 6 years since I've written Java, so please excuse the rust.
I'm working with a library method that requires that I pass it Class objects. Since I'll have to invoke this method a dynamic number of times, each time with a slightly different Class argument, I wanted to pass it an anonymous class.
However, all the documentation/tutorials I've been able to find so far only talk about instantiating anonymous classes, e.g.:
new className(optional argument list){classBody}
new interfaceName(){classBody}
Can I define an anonymous class without instantiating it? Or, perhaps more clearly, can I create a Class object for an anonymous class?
Unfortunately, there's no way you can dodge the instantiation here. You can make it a no-op, however:
foo((new Object() { ... }).getClass());
Of course, this might not be an option if you have to derive from some class that performs some actions in constructor.
EDIT
Your question also says that you want to call foo "each time with a slightly different Class argument". The above won't do it, because there will still be a single anonymous inner class definition, even if you put the new-expression in a loop. So it's not really going to buy you anything compared to named class definition. In particular, if you're trying to do it to capture values of some local variables, the new instance of your anonymous class that foo will create using the Class object passed to it will not have them captured.
short answer
you cannot (using only JDK classes)
long answer
give it a try:
public interface Constant {
int value();
}
public static Class<? extends Constant> classBuilder(final int value) {
return new Constant() {
#Override
public int value() {
return value;
}
#Override
public String toString() {
return String.valueOf(value);
}
}.getClass();
}
let's creating two new class "parametric" classes:
Class<? extends Constant> oneClass = createConstantClass(1);
Class<? extends Constant> twoClass = createConstantClass(2);
however you cannot instantiate this classes:
Constant one = oneClass.newInstance(); // <--- throws InstantiationException
Constant two = twoClass.newInstance(); // <--- ditto
it will fail at runtime since there is only one instance for every anonymous class.
However you can build dynamic classes at runtime using bytecode manipulation libraries such ASM. Another approach is using dynamic proxies, but this approach as the drawback that you can proxy only interface methods (so you need a Java interface).
You can only reference an anonymous class ONCE. If you do not instantiate it there, you cannot instantiate it since you do not have a name for it.
Hence I believe that anonymous classes can only be used in conjunction with a "new BaseClass()".
In your situation you would pass a BaseClass object to your method doing the work, and instantiate the anonymous object in the source code when you need the object to pass.
You can't access the Class object of an anonymous class without instatiating it. However, if you only need access to the class, you could define local classes within your method and refer to these using the ClassName.class literal syntax.
You can assume the name of an anonymous class and call Class.forName("mypackage.MyBaseClass$1") to get a handle to an anonymous class. This will give you the first anonymous class defined in your MyBaseClass, so this is a rather fragile way to refer to a class.
I suspect whatever you are trying to do could be done a better way. What are you really trying to achieve? Perhaps we can suggest a way which doesn't require you to pass a Class this way.
You can access the class object of an anonymous class by calling .getClass() on it immediately after creation. But what good would that do?
I think the key is in this part of what you said:
I'm working with a library method that requires that I pass it Class
objects.
Why does it want you to pass it Class objects? What does this library do with the Class objects you pass it? Instantiate objects? But if so, what constructor does it use and how does it decide what arguments to pass? I don't know what library you are using or what it does, but I would guess that it always creates objects using the no-argument constructor. However, that will not work for anonymous classes anyway, since they have no public constructor (and in any case, to instantiate any non-static inner class, a reference to the outer instance must be provided, so there is no no-argument constructor).

Categories

Resources