Why is it not possible to overload default methods in Interface in Java 8.
The assumption in the question ("Why is it not possible to overload default methods in Interface in Java 8") is just not true. It is perfectly possible to overload an interface's default method. E.g., consider the following code which compiles just fine:
public interface SomeInterface {
default void print(String s) {
System.out.println(s);
}
}
public class SomeClass implements SomeInterface {
/**
* Note the this overloads {#link SomeInterface#print(String)},
* not overrides it!
*/
public void print(int i) {
System.out.println(i);
}
}
We can provide definition for overloaded default method both in interface and in implementing class. Please have a look in below code :-
public class DefaultMethodConflicts2 implements DefInter3,DefInter2 {
public static void main(String[] args) {
new DefaultMethodConflicts2().printme();
new DefaultMethodConflicts2().printmeNew();
new DefaultMethodConflicts2().printme("ashish");
}
/*
If we do not write below method than this step result in error :-
//public class DefaultMethodConflicts2 implements DefInter3,DefInter2 { // <-- error occur --> Duplicate default methods named printme with the parameters () and ()
* are inherited from the types DefInter2 and DefInter3. To check this comment below method.
*/
public void printme() {
DefInter3.super.printme(); // <-- it require to compile the class
}
public void printmeNew() {
System.out.println(" From DefaultMethodConflicts2 :: printmeNew()"); // <-- compile successfully and execute -- line 19
// <---- overloading default method printmeNew() in implementing class as well.
}
}
interface DefInter3 {
default void printme() {System.out.println("from printme3()");}
default void printmeNew() {System.out.println("fFrom DefInter3:printmeNew()");} // <------ if DefaultMethodConflicts2::printmeNew() at line 19 is commented out
// then it will executes.
}
interface DefInter2 {
default void printme() {System.out.println("From DefInter2::()");}
default void printme(String name) {System.out.println("From DefInter2::printme2(String name) "+name);} // <--- Overloading printme() here in interface itself
}
Related
I have an abstract class like
public abstract class EventHandler<T> {
public <T> void preProcess(Message<T> message) {
// do some pre-processing with the Message
}
protected abstract void handleEvent(Message<T> message) throws Exception;
public <T> void postProcess(Message<T> message) {
// do some post-processing with the Message
}
}
There are concrete classes which are extending from this Class.
I want to be able to invoke the preProcess() and postProcess() methods in the Abstract class using an #Around aspect when the handleEvent method is invoked on the concrete class.
I am trying to define the aspect like below
#Aspect
#Configuration
public class SomeAspect {
#Around(value = "execution(* com.handler.EventHandler+.handleEvent(..)))")
public void around(ProceedingJoinPoint proceedingJoinPoint) {
1. invoke preProcess
2. invoke the join point
3. invoke postProcess
}
}
How do i achieve what i am looking for?
Update
#Aspect
#Component
public class SomeAspect {
private Logger logger = LoggerFactory.getLogger(TenantAspect.class);
#Around(value = "execution(* com.handler.EventHandler+.handleEvent(..))) && within(com.handler..*) && this(eventHandler) && args(message))")
public void around(ProceedingJoinPoint proceedingJoinPoint, EventHandler<Object> eventHandler, Message<Object> message) {
}
}
Tried the above and compiler gives Unbound Pointcut Parameter for eventHandler and message
Following Aspect can do the same.
Explanation
execution(* com.handler.EventHandler+.handleEvent(..)) - execution of a method named handleEvent which is in a subtype of EventHandler
Designators
within(com.handler..*) - A scoping desginator to advice classes within the given package
Passing parameters to advice
this(eventHandler) - the object executing the method. target() may also be used
args(message) - argument passed at runtime
Notes
An aspect be better annotated with #Component and #Configuration be used for configurations.
within added to narrow the scope to advice.Please modify as needed
#Aspect
#Component
public class EventHandlerAspect {
#Around(value = "execution(* com.handler.EventHandler+.handleEvent(..)) "
+ "&& within(com.handler..*) "
+ "&& this(eventHandler) "
+ "&& args(message))")
public Object around(ProceedingJoinPoint proceedingJoinPoint,
EventHandler<Object> eventHandler,
Message<Object> message) throws Throwable {
Object obj = null;
// 1. invoke preProcess
eventHandler.preProcess(message);
try {
// 2. invoke the join point
obj = proceedingJoinPoint.proceed();
} finally {
// 3. invoke postProcess
eventHandler.postProcess(message);
}
return obj;
}
}
Hope this helps.
You can get the target object directly from the proceedingJoinPoint as follows:
((TestClass<Integer>) proceedingJoinPoint.getTarget()).preProcess(message);
//or
((TestClass<Object>) proceedingJoinPoint.getTarget()).preProcess(message);
You would need to know the generic's instantiation type and have a matching message object of the same type.
If the message is in the arguments of the intercepted function call you can get them as follows:
Object[] methodArguments = proceedingJoinPoint.getArgs();
Message<Integer> message = (Message<Integer>) methodArguments[0];
If message is the first argument, it will be in methodArguments[0]
interface A {
public void eg1();
}
interface B {
public void eg1();
}
public class SomeOtherClassName implements A, B {
#Override
public void eg1() {
System.out.println("test.eg1()");
}
}
What is the output and what occurs if method is overriden in interface?
First of all it's of no use to implement both class A and B as both
of them has same method signature i.e both has same method name and
return type.
Secondly you'll need a main method to run the program.
Also in interface you can only declare the methods, the implementation
has to be done in the class which implements it.
interface A {
public void eg1();
}
interface B {
public void eg1();
}
public class Test implements A{
#Override
public void eg1() {
System.out.println("test.eg1()");
}
public static void main (String args[]) {
A a = new test();
a.eg1();
}
}
Output : test.eg1()
My app has many RPC calls, and they all have a .onFailure(Throwable caught) method. I have a class shared between the client and the server code NotLoggedInException. This is thrown by the server, if the user doesn't have the relevant permissions based on sessions/cookies/permissions etc.
Ideally I would like to handle this exception in one place BEFORE others are passed to the .onFailure() code, given how ubiquitous this handling is and needs to be for security. There is a GWT.setUncaughtExceptionHandler() but this appears to get called after the handling which isn't ideal (in case an .onFailure accidentally consumes too much).
Does anybody have an elegant solution to this? An ugly solution is to wrap the deferred binded .create() proxy in the same aggregated class implementing the async interface.
Sidenote: The server was issuing a redirect before, but I don't like this paradigm, and would prefer it to be handled by the eventbus of the app.
Update: ugly answer referred to above
public abstract class CustomAsyncCallback implements AsyncCallback{
#Override
public CustomAsyncCallback(AsyncCallback<T> callback)
{
this.wrap = callback ;
}
AsyncCallback<T> wrap ;
#Override
public void onFailure(Throwable caught) {
if (!handleException())
{
wrap.onFailure(caught) ;
}
}
#Override
public void onSuccess(T t) {
wrap.onSuccess(t) ;
}
}
public class WrapDeferredBinding implements RpcInterfaceAsync
{
RpcInterfaceAsync service = GWT.create(RpcInterface.class);
public void method1(int arg1, AsyncCallback<Boolean> callback)
{
service.method1(arg1, new CustomAsyncCallback<Boolean>(callback)) ;
}
public void method2 ....
public void method3 ....
}
In order to wrap every AsynCallback<T> that is passed to any RemoteService you need to override RemoteServiceProxy#doCreateRequestCallback() because every AsynCallback<T> is handed in here before an RPC call happens.
Here are the steps to do so:
To begin you need to define your own Proxy Generator to step in every time a RemoteService proxy gets generated. Start by extending ServiceInterfaceProxyGenerator and overriding #createProxyCreator().
/**
* This Generator extends the default GWT {#link ServiceInterfaceProxyGenerator} and replaces it in the
* co.company.MyModule GWT module for all types that are assignable to
* {#link com.google.gwt.user.client.rpc.RemoteService}. Instead of the default GWT {#link ProxyCreator} it provides the
* {#link MyProxyCreator}.
*/
public class MyServiceInterfaceProxyGenerator extends ServiceInterfaceProxyGenerator {
#Override
protected ProxyCreator createProxyCreator(JClassType remoteService) {
return new MyProxyCreator(remoteService);
}
}
In your MyModule.gwt.xml make use of deferred binding to instruct GWT to compile using your Proxy Generator whenever it generates something of the type RemoteService:
<generate-with
class="com.company.ourapp.rebind.rpc.MyServiceInterfaceProxyGenerator">
<when-type-assignable class="com.google.gwt.user.client.rpc.RemoteService"/>
</generate-with>
Extend ProxyCreator and override #getProxySupertype(). Use it in MyServiceInterfaceProxyGenerator#createProxyCreator() so that you can define the base class for all the generated RemoteServiceProxies.
/**
* This proxy creator extends the default GWT {#link ProxyCreator} and replaces {#link RemoteServiceProxy} as base class
* of proxies with {#link MyRemoteServiceProxy}.
*/
public class MyProxyCreator extends ProxyCreator {
public MyProxyCreator(JClassType serviceIntf) {
super(serviceIntf);
}
#Override
protected Class<? extends RemoteServiceProxy> getProxySupertype() {
return MyRemoteServiceProxy.class;
}
}
Make sure both your MyProxyCreator and your MyServiceInterfaceProxyGenerator are located in a package that will not get cross-compiled by GWT into javascript. Otherwise you will see an error like this:
[ERROR] Line XX: No source code is available for type com.google.gwt.user.rebind.rpc.ProxyCreator; did you forget to inherit a required module?
You are now ready to extend RemoteServiceProxy and override #doCreateRequestCallback()! Here you can do anything you like and apply it to every callback that goes to your server. Make sure that you add this class, and any other class you use here, in my case AsyncCallbackProxy, to your client package to be cross-compiled.
/**
* The remote service proxy extends default GWT {#link RemoteServiceProxy} and proxies the {#link AsyncCallback} with
* the {#link AsyncCallbackProxy}.
*/
public class MyRemoteServiceProxy extends RemoteServiceProxy {
public MyRemoteServiceProxy(String moduleBaseURL, String remoteServiceRelativePath, String serializationPolicyName,
Serializer serializer) {
super(moduleBaseURL, remoteServiceRelativePath, serializationPolicyName, serializer);
}
#Override
protected <T> RequestCallback doCreateRequestCallback(RequestCallbackAdapter.ResponseReader responseReader,
String methodName, RpcStatsContext statsContext,
AsyncCallback<T> callback) {
return super.doCreateRequestCallback(responseReader, methodName, statsContext, new AsyncCallbackProxy<T>(callback));
}
}
Now, your AsyncCallbackProxy can look something like this:
public class AsyncCallbackProxy<T> implements AsyncCallback<T> {
private AsyncCallback<T> delegate;
public AsyncCallbackProxy(AsyncCallback<T> delegate) {
this.delegate = delegate;
}
#Override
public final void onFailure(Throwable caught) {
GWT.log("AsyncCallbackProxy#onFailure() : " + caught.getMessage(), caught);
if (caught instanceof NotLoggedInException) {
// Handle it here
}
delegate.onFailure(proxy);
}
#Override
public final void onSuccess(T result) {
delegate.onSuccess(result);
}
}
References:
DevGuideCodingBasicsDeferred.html
An example applied to performance tracking
You can wrap AsyncCallback class with an abstract class:
public abstract class CustomAsyncCallback<T> implements AsyncCallback<T>{
#Override
public void onFailure(Throwable caught) {
GWT.log(caught.getMessage());
handleException();
this.customOnFailure(yourDesireParam);
}
/**
* this method is optional
*/
public abstract void customOnFailure(Param yourDesireParam);
}
And then send a CustomAsyncCallback object to your RPC asynch methods.
i was recently digging on new partial methods in c#3.0, i understood the use of partial class, that it could be chunked into multiple file one contain the definition and other declaration, but i wanted to know,i created a partial class like below:
in class1.cs
partial class A
{
partial void Method();
}
in class2.cs
partial class A
{
partial void Method()
{
Console.WriteLine("Hello World");
}
}
now in class3.cs
class MainClass
{
static void Main()
{
A obj = new A();
obj.Method(); //Here i cannot call the "Method" method.
}
}
then whats the use of creating partial method, i read on MSDN that, at runtime, compiler compiles the class into one, in that case compiler should be getting the "Method" method implementation also, then why it dont allow me to call the "Method" method in the main method, can anyone correct me if i am wrong, and tell me why i am unable to call this partial method in main.
From MSDN
No access modifiers or attributes are allowed. Partial methods are
implicitly private.
It's a private method, so you can't call it from main.
You can call a partial method inside the constructor where the method is defined.
For example
public partial class classA
{
partial void mymethod();
}
public partial class classA
{
partial void mymethod()
{
Console.WriteLine("Invoking partial method");
}
public ClassA()
{
mymethod();
}
}
public class MainClass
{
static void Main()
{
ClassA ca=new ClassA();
}
}
That's it..now execute your code and see the result..
OutPut
Invoking partial method
Yes, we can't call it from Main(). Problem is not Partial method problem is method without specifier in a class is Private and private method can be called inside the class only.
Try creating a new public method in Partial class:
partial class A
{
partial void Method();
}
partial class A
{
partial void Method()
{
Console.WriteLine("Hello World");
}
public void Study()
{
Console.WriteLine("I am studying");
Method();
}
}
class MainClass
{
static void Main()
{
A obj = new A();
obj.Study();
}
}
(This is .Net 3.5) I have a class FooList which implements IList and a class FooClass which implements IFoo. A user requires IList<IFoo>. In my implementation, I create a FooList<FooClass>, called X. How do I code my return so that my FooList<FooClass> X becomes his IList<IFoo>?
If I try
return X.Cast( ).ToList( );
he gets an IList<IFoo>, but it is not my FooList; it is a List, and a new one at that.
This isn't going to work out, because a FooList<FooClass> is not an IList<IFoo>. This is why:
var myList = new FooList<FooClass>();
IFoo obj = new SomeOtherFooClass();
IList<IFoo> result = (IList<IFoo>)myList; // hypothetical, wouldn't actually work
result.Add(obj); // uh-oh, now myList has SomeOtherFooClass
You need to either make a copy or use an interface that is actually covariant on the contained type, like IEnumerable<T> instead of IList<T>. Or, if appropriate, you should declare your FooList<FooClass> as an FooList<IFoo> from the get-go instead.
Here is a small implementation that demonstrates my second suggestion:
public interface IFoo { }
public class FooClass : IFoo { }
public class FooList<T> : IList<T>
{
public void RemoveAt(int index) { /* ... */ }
/* further boring implementation of IList<T> goes here */
}
public static void ListConsumer(IList<IFoo> foos)
{
foos.RemoveAt(0); // or whatever
}
public static IList<IFoo> ListProducer()
{
// FooList<FooClass> foos = new FooList<FooClass>(); // would not work
FooList<IFoo> foos = new FooList<IFoo>();
foos.Add(new FooClass());
return foos; // a FooList<IFoo> is an IList<IFoo> so this is cool
}
public static void Demo()
{
ListConsumer(ListProducer()); // no problemo
}