c# Anonymous Interface Implementation [duplicate] - java

This question already has answers here:
C# equivalent of creating anonymous class that implements an interface
(2 answers)
Closed 4 years ago.
i've already seen this question a few times but i still don't get it.
In Java, i can do this:
new Thread(new Runnable(){
#Override
public void run() {
System.out.println("Hello");
}
}).start();
In my opinion, this is a very nice way to implement interfaces which implementations are only used once. Is there a way to do this in C#?
I've already heard of delegates, but that only solves the problems partly since i can only implement one method. What is the "right" way to do that in C# if i have multiple methods? Do i have to implement another class for that?
Thanks in Advance!
-Chris
EDIT:
I don't want to make a new thread specifically. That was a more general question about the right way to do something like an anonymous implementation from Java in C#. It's not about that specific example.

The general way to do this is C# is to create your own private class. As you noted, other approaches in C# (delegate/lambda) only work when the interface has just one method (i.e., a Java functional interface):
Java:
void testMethod()
{
x = new ISomeInterface(){
#Override
public void method1() { foo(); }
#Override
public void method2() { bar(); }
};
}
C#:
void testMethod()
{
x = new ISomeInterfaceAnonymousInnerClass();
}
private class ISomeInterfaceAnonymousInnerClass : ISomeInterface
{
public void method1()
{
foo();
}
public void method2()
{
bar();
}
}
Here is the simplest conversion when a Java functional interface is involved:
Java:
#FunctionalInterface
interface ISomeInterface
{
void method();
}
void testMethod()
{
x = new ISomeInterface(){
#Override
public void method() { foo(); }
};
}
C#:
delegate void ISomeInterface();
void testMethod()
{
x = () =>
{
foo();
};
}

Probably you've searched this before and by now the answer is: No. Noway in C#
But I think your main question is Why?
Short Answer: It can be designed in the next C# versions as a feature. It's absolutely possible.
Long Answer: If you want more details on why it's not added to the C# yet; there is a helpful conversation below this exact feature request in the Roslyn (an open-source .Net complier) page at GitHub. Check it out: https://github.com/dotnet/roslyn/issues/13

Related

Java Delegate Interface

Is there a simple Interface in Java like the following code?
public interface Delegate {
void action();
}
Java Delegates? describes the functionality well.
It's not a Supplier, not a Consumer, not a Function, not a Runnable(no async stuff needed), I just want to pass a lambda to a method to be executed in between common parts.
Now I'm wondering why I have to define this interface myself. Am I just unable to find the standard Java interface for this or am I missing some vital drawback here?
Usage in my code (simplified):
public void transferX(Xrequest request){
transfer(request, () -> this.typedWrite(request));
}
public void transferY(Yrequest request){
transfer(request, () -> this.typedWrite(request));
}
void transfer(BaseRequest request, final Delegate writeFunction){
...
try{
writeFunction.action();
...
catch(...){...}
}
void typedWrite(Xrequest request){...}
void typedWrite(Yrequest request){...}
OK, as Sweeper pointed out, that is just the Runnable interface. I just don't like the naming, since I immediately associate it with multithreading.
For comparison:
#FunctionalInterface
public interface Runnable {
public abstract void run();
}

How is the interface being instantiated, without implementation of any class? [duplicate]

This question already has answers here:
Can we create an instance of an interface in Java? [duplicate]
(7 answers)
Closed 2 years ago.
public interface InterfaceTest {
interface Gift { void present(); }
interface Guest { void present(); }
interface Presentable extends Gift, Guest { }
public static void main(String[] args) {
Presentable johnny = new Presentable() {
#Override public void present() {
System.out.println("Heeeereee's Johnny!!!");
}
};
johnny.present();
((Gift) johnny).present();
((Guest) johnny).present();
Gift johnnyAsGift = (Gift) johnny;
johnnyAsGift.present();
Guest johnnyAsGuest = (Guest) johnny;
johnnyAsGuest.present();
}
}
This code compiles and runs the main() function without error, what concept am I missing here?
johnny is an instance of an anonymous subclass. From the link:
Anonymous classes enable you to make your code more concise. They
enable you to declare and instantiate a class at the same time. They
are like local classes except that they do not have a name. Use them
if you need to use a local class only once.
The reason your code compiles is because the implementation of present is provided in this anonymous subclass. To drive the point further, this:
Presentable johnny = new Presentable();
would not compile. However, this:
Presentable johnny = new Presentable() {
#Override public void present() {
// Do something
}
};
is perfectly valid.

Calling a method in ExecuterService using double colon (::) [duplicate]

This question already has answers here:
:: (double colon) operator in Java 8
(17 answers)
Closed 2 years ago.
I have a class constitues 2 methods static and non static respectively, as per my limited knowledge submit method accepts runnable,callable instance directly or through lamba expression.
Today I came to know that we can even call or trigger static as well as non static method directly by using double colon which has been added in java 8.
I was just wondering how this works, there is no run method in my class and it doesn't implements runnable and even I'm not using lamba?
Is it a good practice to use :: or one should pass the runnable or callable instance.
Is there any other way to call a method inside submit() rather passing an instance?
Class A {
public static void printSomething(){
System.out.println("Staitc Method");
}
public void print()
{
System.out.println("Non-Staitc Method");
}
}
psvm()
{
A a = new A():
ExecutorService es = Executors.newFixedThreadPool(2);
es.submit(A::printSomething); //Expected is runnable or callable task
es.submit(a::print);
}
A::printSomething is called a method reference. When you use a method reference in a place that expects an interface like Runnable or Callable, Java automatically creates an implementation of that interface that calls the method.
That is,
es.submit(A::printSomething);
behaves the same as
es.submit(new Runnable() {
public void run() {
A.printSomething();
}
});
but is easier to read and does not create a new class everywhere you use it, or a new object instance every time it's called.
You can read more about method references in
The tutorial from Oracle
This write-up on Baeldung
Another way of achieving the same is using lambda expressions such as:
es.submit(() -> A.printSomething());
Since Runnable is a functional interface, you can use lambda expressions or method references that fit it even if the method name doesn't match. Therefore any no-arg void method can be used as a Runnable.
Runnable r1 = () -> a.printSomething();
Runnable r2 = A::printSomething(); // Method reference, short-hand
Runnable r3 = () -> A.printSomething(); // Same as r2, but as explicit lambda expression
The reason why the method reference works even though the class does not implement a void run() method is because what matters for Functional Interface assignment is the method signature and not the method names.
The method signature of A's printSomething matches Runnable's run and for that reason it works. Notice this only works with Functional Interfaces (i.e. those with only one method, said method method not having a default implementation).
Is it good practice? It's a matter of style but it is definitely not bad practice to use method references, and they're also more concise than left -> right lambdas.
I suggest you try this out yourself so you're clear on the rules.
public class FunctionalInterfaceDemo {
public static class SimpleClass {
public static void doItStatic() {
}
public void doItNonStatic() {
}
}
interface MyOwnFunctionalInterface {
void methodA();
}
interface NotAFunctionalInterface {
void methodA();
void methodB();
}
interface AlsoNotAFunctionalInterface {
default void methodA() {
}
}
public static void main(String[] args) {
MyOwnFunctionalInterface compiles = SimpleClass::doItStatic;
MyOwnFunctionalInterface alsoCompiles = new SimpleClass()::doItNonStatic;
NotAFunctionalInterface doesNotCompile = SimpleClass::doItStatic;
AlsoNotAFunctionalInterface alsoDoesNotCompile = SimpleClass::doItStatic;
}
}

How to access method from two classes which do not share an interface?

I am creating a java library that will access web services, but the library will be called in different platforms, so we are using ksoap2 and ksoap2-android to generate helper classes for the different platforms. The problem is that we then have two sets of generated classes/methods whose signatures are equivalent, but which do not overtly share a Java Interface - so I can't figure a way to call them from my main code.
A simplified example:
//generated for Android
class A {
public String sayHi() {
return "Hi A";
}
}
//generated for j2se
class B {
public String sayHi() {
return "Hi B";
}
}
//main code - don't know how to do this
XXX talker = TalkerFactory.getInstance()
String greeting = talker.sayHi()
Of course, that last part is pseudo-code. Specifically, how can I call sayHi() on an instance of an object which I don't know the type of at compile time, and which does not conform to a specific interface? My hope is that there is some way to do this without hand editing all of the generated classes to add an "implements iTalker".
The straightforward way is to use an adapter.
interface Hi {
void sayHi();
}
public static Hi asHi(final A target) {
return new Hi() { public void sayHi() { // More concise from Java SE 8...
target.sayHi();
}};
}
public static Hi asHi(final B target) {
return new Hi() { public void sayHi() { // More concise from Java SE 8...
target.sayHi();
}};
}
In some circumstance it may be possible, but probably a bad idea and certainly less flexible, to subclass and add in the interface.
public class HiA extends A implements Hi {
}
public class HiB extends B implements Hi {
}

Dynamic Function Creation in Java

So I'm trying to figure out if there is some method to dynamically create/assign a method to a class in Java. If it were C, I would just do it as follows using pointers:
public class Foo {
void bar(void *ptr) {....}
};
int main() {
Foo f = new Foo();
f.bar({"my function" ...})
}
However, Java of course has no pointers, so is there any way to get a similar functionality out of a Java application?
In Java, you would normally declare an interface with a method to be called. For example, if your function simply wants to execute some code, you would declare a Runnable and implement its run method.
public class Foo {
void bar(Runnable function) {
for(int i = 0; i < 5; i++) {
function.run();
}
}
static void myFunction() {
System.out.println("my Function!");
}
public static void main(String[] ignored) {
Foo f = new Foo();
f.bar( new Runnable() { public void run() {
myFunction();
}});
}
}
To generate truly dynamic methods you need a bytecode-manipulation library, such as Javassist or cglib.
In java it is achieved by something called anonymous classes, here is an example -
abstract class Bar {
public void myfunc();
}
public class Client {
public void execute()
{
doSomething(new Bar() {
// define your dynamic function here ie provide its implementation
public void myfunc() {
//do whatever
}
});
}
public void doSomething(Bar b)
{
b.myfunc();
}
}
You can use the Java Scripting API, create the function as a Script and call it. But only do this if your functions are really completely defineable at runtime, because interpreting scripts is always slower than implementing it in native Java.
If you really want to change classes at runtime, the only way is to actually modify the bytecode, assuming your set-up allows it (Java security would normally kick in). That said, there's an java.lang.instrument package in Java 6 which may help:
http://download.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html
You might find the cglib project of use also:
http://sourceforge.net/projects/cglib/
See http://functionaljava.org/ for a whole functional library for Java.
Here's a link to how you can use the built in runtime version of javac to compile classes you define on the fly.

Categories