Java custom warnings - java

Hello I wanted to throw a custom warning. Say i have
public abstract class A {
public void doSomething() {
//base functionality
}
}
public class B extends A {
#Override
public void doSomething() {
super.doSomething();
//extended functionality
}
}
public class C extends A {
}
i want to throw an error for class C because it does not override the method. Normally an abstract method would suffice but the method contains functionality common to all subclass and if there is a better standard or structure please let me know.
I want to force all subclasses to #Override that certain method
I have looked into creating a custom annotation like
public #interface ShouldOverride
but i could not figure out how to throw a warning with that.
Note. I am using IntelliJ Idea Ultimate

Implementation of the proposition of Thomas:
abstract class A {
public void doSomething() {
// basic things to do
// then call implementation
doSomethingImpl();
}
protected abstract void doSomethingImpl();
}
class B extends A {
#Override
protected void doSomethingImpl() {
//extended functionality
}
}
class C extends A { // does not compile
}

Related

java interface method removing from subclass

Anyone provide suggestion for below mentioned:
in java8 consider an interface having two methods (eg interface1 ,interface 2)
implementing those to many subclass later i want to remove one method interface1 from one of my subclass without affecting other is any possible solution is there?
If your subclass declares that it implements this interface, then you have no choice but to provide implementations for all methods, or declare the class abstract. If you want a concrete class which however does not functionally implement all methods in the interface, then here is one option:
public interface YourInterface {
void method1();
void method2();
}
public class YourSubClass implements YourInterface {
#Override
public void method1() {
// actually do something
}
#Override
public void method2() {
throw new UnsupportedOperationException("method2() is not supported here.");
}
}
Here while we do implement all methods, we throw a runtime exception should a caller try to access method2().
You can do this by providing a default method implementation for the interface1 method in the interface itself.
interface Interface {
default void interface1() {
System.out.println("interface1");
}
void interface2();
}
class Clazz implements Interface {
#Override
public void interface2() {
System.out.println("interface2");
}
}
Depends how you define 'remove one method'.
If you have interface
interface Interface{
void interface1();
void interface2();
}
And for example two subclasses that extend it:
class Class1 implementes Interface {
#Override
public void interface1(){ ... }
#Override
public void interface2(){ ... }
}
class Class2 implementes Interface {
#Override
public void interface1(){ ... }
#Override
public void interface2(){ ... }
}
Then there are two scenarios:
You don't want to implement for example interface1() method in Class2:
You don't want to have interface1() method in Class2
In case of 1. as Robby Cornelissen mentioned, you can simply provide default implementation in Interface:
default void interface1() { /*do default thing*/ }
In case of 2. you need to remove the interface1() method from the Interface.
You can do that by simple moving definition of method interface1() to Class1 (and any other sublass that needs to have it). but that is not really generic approach.
Best is to extract for example Interface1 with method interface1() and use that interface in classes that need to have that method. You will end up with this situation:
interface Interface{
void interface2();
}
interface Interface1{
void interface2();
}
And for example two subclasses that extend it:
class Class1 implementes Interface, Interface1 {
#Override
public void interface1(){ ... }
#Override
public void interface2(){ ... }
}
class Class2 implementes Interface {
#Override
public void interface2(){ ... }
}

Java: How can I design this class for having optional generics ParameterType?

I have this class in my code
public abstract class MyAbstractEventListener<E extends IMyEvent> {
public abstract void handleEvent(E e);
}
and I can make instances in this way (let's call it A):
new MyAbstractEventListener<IMyEvent>() {
#Override
public void handleEvent(final IMyEvent e) {
// Method implementation
}
};
But for my purposes, it would be ideal being able also to do this as well when there's no required event info (let's call this B):
new MyAbstractEventListener() { // Or receiving some unused parameter
#Override
public void handleEvent() {
// Method implementation
}
};
without having the warning about the class being raw and reccomending to parameterize it.
To clarify, I want the class to allow either the A or B instantiation, having the personal choice of using the one I prefer each time. If there's some generics parameter, the method receiving the IMyEvent object and if not, the method without parameters.
An example of code using this class would be:
EventBus.getInstance().addEventListener("some.string", new
AbstractEventListener<IMyEvent>() {
#Override
public void handleEvent(final IMyEvent e) {
// Sometimes does use 'e', sometimes doesn't. That's the point
MyConfirmationWindow.showConfirmationWindow(MyWindowType.WARNING, "kk", "lll");
}
});
Is there a way? Any link or resource will be appreciated.
Well, you could make an abstract subclass :
public abstract class BlindListener extends MyAbstractEventListener<IMyEvent> {
public abstract void handleEvent();
#Override
public void handleEvent(IMyEvent iMyEvent) {
handleEvent(); // delegate to abstract method that ignores the argument
}
}
This is actually a class that uses generics, but clients won't ever have to deal with them :
new BlindListener() {
#Override
public void handleEvent() {
}
}
Instances that do need a specific type can still use the MyAbstractEventListener directly
I don't think you will be able to avoid having tow handleEvent methods the way you described here.
But here is another approach using Null Object design pattern and single handleEvent method:
new MyAbstractEventListener<IMyEvent>() {
#Override
public void handleEvent(final IMyEvent e) {
// Method implementation
}
};
new MyAbstractEventListener<NullIMyEvent>() {
#Override
public void handleEvent(final NullIMyEvent e) {
// Method implementation
}
};
public interface IMyEvent{}
public class NullIMyEvent implements IMyEvent{}
public static abstract class MyAbstractEventListener<E extends IMyEvent> {
public abstract void handleEvent(E e);
}
public abstract class MyAbstractEventListener<E extends IMyEvent> {
But for my purposes, it would be ideal being able also to do this as well when there's no required event info (let's call this B):
The question is: what does the class MyAbstractEventListener do with the information that the parameter type E extends IMyEvent? Is there any method in that class working on type IMyEvent?
If not you could simple remove extends IMyEvent to achieve your goal.
Otherwise you need a different class since MyAbstractEventListener relies on type Eextending (or implementing) IMyEvent.

How to invoke an interface's default implementation of a method in an overriding implementation?

Suppose I have the following code:
interface HumanoidForm {
default HumanoidForm reproduce() {
<appropriate code for humanoid form reproduction>
}
}
class Android extends Machine implements HumanoidForm {
public HumanoidForm reproduce() {
<appropriate code for android reproduction> // how to use HumanoidForm's default implementation here?
}
}
Now suppose "appropriate code for android reproduction" is best described by using "appropriate code for humanoid form reproduction" as a sub-routine. How can I access "appropriate code for humanoid form" from within "appropriate code for android reproduction"? I can think of three ways, but none of them works:
Simply invoking reproduce() invokes the overriding implementation.
Writing ((HumanoidForm) this).reproduce() still invokes the overriding implementation.
Mimicking the re-use of implementations of methods in super classes by overriding methods, one may think of writing super.reproduce(). However, that refers to Machine's implementation of reproduce, which may not even exist.
So it seems there is no way to re-use the code in the default method for overriding. Is that really so?
HumanoidForm.super.reproduce();
Actually, you can choose freely the existing implementation. Let me give you a scenario slightly more complicated than yours. To make things worse, all A,B & C has the same method signature.
interface A {
default void doWork() {
System.out.println("Default implementation From A");
}
}
interface B{
default void doWork() {
System.out.println("Default implementation From B");
}
}
class C{
void doWork(){
System.out.println("Default implementation From C");
}
}
Now, I create a subclass to C which implements A & B:
class Tester extends C implements A, B
{
#Override public void doWork(){
A.super.doWork(); //Invoke A's implementation
B.super.doWork(); //Invoke B's implementation
super.doWork(); //Invoke C's implementation
}
}
The output will be:
Default implementation From A
Default implementation From B
Default implementation From C
when you run:
new Tester().doWork();
Take a look at this: https://blog.idrsolutions.com/2015/01/java-8-default-methods-explained-5-minutes/
In particular the section where it says "If we want to specifically invoke one of the sayHi() methods in either InterfaceA or InterfaceB, we can also do as follows:"
public class MyClass implements InterfaceA, InterfaceB {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
#Override
public void saySomething() {
System.out.println("Hello World");
}
#Override
public void sayHi() {
InterfaceA.super.sayHi();
}
}
interface InterfaceA {
public void saySomething();
default public void sayHi() {
System.out.println("Hi from InterfaceA");
}
}
interface InterfaceB {
default public void sayHi() {
System.out.println("Hi from InterfaceB");
}
}
So it seems there is no way to re-use the code in the default method for overriding. Is that really so?
No, you can reuse the code. You can easily test it and you will see that the following code works:
public class Test implements HumanoidForm
{
public static void main(String[] args)
{
new Test().reproduce();
}
#Override
public void reproduce(){
HumanoidForm.super.reproduce(); //Invoking default method
System.out.println("From implementing class");
}
}
interface HumanoidForm {
default void reproduce() {
System.out.println("From default interface");
}
}
OUTPUT:
From default interface
From implementing class

Java wrapper: overriding a method called in the super constructor

I want to wrap a class in Java but the problem is as follows:
public class A {
public A() {
doSomething();
}
public void doSomething() {
}
}
Now when I try to wrap this class and delegate all methods to the wrapper
public class Wrapper extends A {
private final A a;
public Wrapper(A a) {
super();
this.a = a;
}
#Override
public void doSomething() {
this.a.doSomeThing();
}
}
of course I get a NPE as 'a' is still null as it is set after the super()-call which calls the overriden doSomething() method. Is there any solution for this problem? The only thing that came to my mind was making a factory method and setting a static variable holding the reference to a but this seems ugly to me.
I'd recommend changing the code so that doSomething is not called in the constructor.
Alternatively split A into an interface and implementation Wrapper implements the interface and does not inherit from A
public interface IA {
public void doSomething() {
}
}
public class A implements IA {
public A() {
doSomething();
}
public void doSomething() {
}
}
public class Wrapper implements IA {
private final IA a;
public Wrapper(IA a) {
this.a = a;
doSomething();
}
#Override
public void doSomething() {
a.doSomeThing();
}
}
Change your Wrapper this way. You do not need to hold A explicitly. The expression super is the same as your filed:
class Wrapper extends A {
public Wrapper() {
}
#Override public void doSomething() {
super.doSomething();
}
}
Or otherwise extract an interface and change your code like this:
class Wrapper implements AA {
private final AA child;
public Wrapper(AA child) {
this.child = child;
}
#Override public void doSomething() {
child.doSomething();
}
}
class A implements AA {
public A() {
doSomething();
}
#Override public void doSomething() {}
}
interface AA {
public void doSomething();
}
A way for this to be avoided is by exposing an init method (or any other name) from your base class (if you are in control of its logic). Then move the call from the constructor to the init method:
public class A {
public A() {
}
public void init() {
doSomething();
}
public void doSomething() {
}
}
You should update your code to call the init method after making an instance of the class, which may be a bit of boilerplate:
A instance = new Wrapper();
instance.init();
instead of just
A instance = new Wrapper();
If you use Spring and DI, you can specify an init-method in the xml context, so Spring will call it for you when it resolves the dependency.
In case the doSomething method is public, and accepts no arguments, you can use it directly instead of the init method both in code and with Spring.
In general, use of overridable methods in a constructor is an anti-pattern, due to the problem you have encountered. There is no way to predict how a derived class will override the methods and if they rely on non-initialized resources, then you are in trouble.
two small changes, young one you need
public class Wrapper extends A {
private final A a;
public Wrapper(A a) {
super();
this.a = a;
//this will execute method doSomething wrom Wrapper class after variable a is set
doSomething();
}
#Override
public void doSomething() {
//this will prevent to call metod from superclass constructor, bit risky thou
if (a!=null)
this.a.doSomething();
}
}
but overriding methods which are called in constructo is generally bad practice and smells terrible

Inheritance and Multiple Collaborators

I have several Java interfaces/ABCs/classes:
public abstract class Target {
public abstract void fire(Load load);
}
public class HttpTarget extends Target {
#Override
public void fire(Load load) {
// ...
}
}
public interface Load {
// ...
}
public class HttpLoad implements Load {
// ...
}
// Inside a driver
Target target = testSuite.getTarget();
Load load = testSuite.getLoad();
target.fire(load);
So essentially a Target can fire() a Load. My main app Driver doesn't care about what kind of Target is returned by getTarget(), or what kind of Load is returned by getLoad(). It's job is to make sure that a load is fired.
I'd like to change the fire() method definition inside HttpTarget to:
#Override
public void fire(HttpLoad httpLoad) {
// ...
}
However when I do that, Java complains that the method override doesn't match the definition provided by its parent Target class (as Load and HttpLoad are two different things).
What's the solution here? Generics? Abstract factories? Ultimately, I want to be able to enforce that HttpTarget's fire() method can only accept HttpLoads, but still be compatible with the Driver code. Can someone provide a code example? Thanks in advance!
Yes, you would need generics:
public abstract class Target<L extends Load> {
public abstract void fire(L load);
}
public class HttpTarget extends Target<HttpLoad> {
#Override
public void fire(HttpLoad load) {
...
}
}
public interface TestSuite<L extends Load> { // or class
L getLoad();
Target<L> getTarget();
}
public class HttpTestSuite implements TestSuite<HttpLoad> {
#Override
public HttpLoad getLoad() {
...
}
#Override
public Target<HttpLoad> getTarget() {
return new HttpTarget();
}
}
The reason Java refuses to compile your HttpTarget class is because it doesn't override the Target's fire(Load) method. Indeed, a Target, by contract is supposed to accept any kind of Load as argument. And the HttpTarget's fire() method only accepts instances of HttpLoad, and thus breaks the Liskov principle. Generics are the solution to this problem.
You will have to use generics and even then it is not exactly what you want.
public interface Load<T extends Load> {
public void someMethod();
}
public class HttpLoad implements Load<HttpLoad> {
#Override
public void someMethod() {
System.out.println("Http Load");
...
}
}
public abstract class Target<T extends Load> {
public abstract void fire(Load<T> load);
}
public class HttpTarget extends Target<HttpLoad> {
#Override
public void fire(Load<HttpLoad> load) {
load.someMethod();
}
}
Now if you write
Target<HttpLoad> httpTarget = new HttpTarget();
Load<HttpLoad> httpLoad = new HttpLoad();
Load<OtherLoad> otherLoad = new OtherLoad();
Load otherLoad2 = new OtherLoad();
httpTarget.fire(httpLoad);
httpTarget.fire(otherLoad); // this doesn't compile
httpTarget.fire(otherLoad2) // this how ever compiles

Categories