Anonymous interface implementation - java

I´ve read 'C# anonymously implement interface (or abstract class)' thread for implementing an interface anonymously. But I wondered if this is also possible using .NET 2.0 (NO LINQ) using delegates or any similar approach. I know from JAVA the following possible:
MyClass m = MyMethod(new MyInterface() {
#override
public void doSomething() {...}
}
(I hope I remember well, is a time ago that I used JAVA, but I suppose it was something similar). This might be helpful whenever a method needs an instance of an interface and is called only once so there is no need to create a new class for this single approach.

.NET 2.0 also supported anonymous delegates, it's just that the syntax was a bit more verbose compared to lambdas, and type inference didn't work. And there were no extension methods in C# 2.0 (although you were able to use C# 3.0 and compile against .NET 2.0), which are the basis of LINQ and being able to operate on interfaces.
Compare:
.NET 2.0: delegate(int i) { return (i < 5); }
.NET 3.5: i => i < 5
.NET 2.0 also lacks common generic delegate signatures (Func and Action), but you can also easily define them yourself (for all combinations of parameters you like):
public delegate void Action<T>(T item);
public delegate Tresult Func<T, Tresult>(T item);
So, whatever approach your linked answer used to mimic anonymous interfaces can be represented using .NET 2.0 delegates, at the expense of added verbosity. Making you ask yourself: "is this really that shorter to write?"
[Update]
If your interface is a single method interface, like:
interface IFoo
{
string Bar(int value);
}
class SomeOtherClass
{
void DoSomething(IFoo foo);
}
then you might get rid of it entirely and simply use a delegate instead:
class SomeOtherClass
{
void DoSomething(Func<int, string> bar);
}
new SomeOtherClass().DoSomething(delegate(int i) { return i.ToString(); });
If you have an interface with many methods that you want to be able to implement inline in many different places, you can use something like this:
interface IFoo
{
string GetSomething();
void DoSomething(int value);
}
// conditional compile, only if .NET 2.0
#if NET_2_0
public delegate void Action<T>(T item);
public delegate Tresult Func<Tresult>();
#endif
class DelegatedFoo : IFoo
{
private readonly Func<string> _get;
private readonly Action<int> _do;
public DelegatedFoo(Func<string> getStuff, Action<int> doStuff)
{
_get = getStuff;
_do = doStuff;
}
#region IFoo members simply invoke private delegates
public string GetSomething()
{ return _get(); }
public void DoSomething(int value)
{ _do(value); }
#endregion
}
Which would allow you to pass delegates to the DelegatedFoo class inline:
var delegated = new DelegatedFoo(
delegate() { return ""; }, // string GetSomething()
delegate(int i) { } // void DoSomething(int)
);
Using .NET 4 the C# 4.0 syntax it would look a bit cleaner due to syntactic sweetness of lambdas and named parameters:
var delegated = new DelegatedFoo(
getStuff: () => "",
doStuff: i => { }
);

I know that this may not be exactly what you are hoping for, but if you absolutely have to do it, you can use any of the mocking frameworks available to request an object which implements the interface and then add implementations for the methods. This is a standard practice in TDD.
Also, you can simply use anonymous delegates to achieve most of your needs as per John Skeet's advice in the question your mention.

Related

Different ways of Implementing Interface in C# vs Java [duplicate]

I am wondering if there is some inline short way of creating a class implementing a interface. Just like there are the anonymous methods but with implementing interfaces.
The problem is:
interface iSomeInterface
{
void DoIt();
}
public void myMethod(iSomeInterface param)
{
...
}
And I would like to use it like this:
object.myMethod(new { override DoIt() { Console.WriteLine("yay"); } } : iSomeInterface);
Any ideas?
Sorry in case its a duplicate.
Sorry, no inline implementation of classes in C#. There are only Anonymous Types, but they don't support adding interfaces (see for example Can a C# anonymous class implement an interface?) (nor they support adding methods or fields... They only support properties).
You can use the methods of System.Reflection.Emit to generate a class at runtime, but it's long and tedious.
You can create a class that wraps an Action and implements that interface:
public sealed class SomeAction : ISomeInterface
{
Action action;
public SomeAction (Action action) { this.action = action; }
public void DoIt() { this.action(); }
}
This allows you to use it as follows:
object.myMethod(new SomeAction(() => Console.WriteLine("yay"));
This is of course only very practical if you are going to reuse SomeAction, but this is probably the most convenient solution.
That is pretty common in java but there is no way you can do it in C#. You can pass a functions or procedures as parameters though:
public void myMethod(Action act)
{
act();
}
myMethod( () => Console.WriteLine("yay") );
Several (generic) version of Action (procedure with parameters and no return value) and Func (functions with parameters and return value) exist.
Look for the "ImpromptuInterface" NuGet package.
With the combination of this package and ExpandoObject, you can do something like this
//Create an expando object and create & assign values to all the fields that exists in your interface
dynamic sigObj = new ExpandoObject();
sigObj.EmployeeKey = 1234;
//Create the object using "ActLike" method of the Impromptu class
INewSignatureAcquired sig = Impromptu.ActLike<INewSignatureAcquired>(sigObj);

Call method on template argument without knowing a base class in Java

I would like to write a generic algorithm, which can be instantiated with different objects. The objects are coming from 3rdparty and they have no common base class. In C++, I just write the generic algorithm as a template which takes the particular object as its argument. How to do it in Java?
template <class T>
class Algorithm
{
void Run(T& worker)
{
...
auto value = workder.DoSomething(someArgs);
...
}
};
In C++, I don't need to know anything about the T, because the proper types and availability of methods are checked during compilation. As far as I know,
in Java I must have a common base class for all my workers to be able to call methods on them. Is it right? Is there a way how to do similar stuff in Java?
I can't change my 3rdparty workers, and I don't want to make my own abstraction of all workers (including all types which the workers are using, etc.).
Edit:
Since I want to write the generic algorithm only once, maybe it could be a job for some templating language which is able to generate Java code (the arguments to the code template would be the workers)?
My solution:
In my situation, where I cannot change the 3rdparty workers, I have chosen Java code generation. I have exactly the same algorithm, I only need to support different workers which all provides identical interface (classes with same names, same names of methods, etc.). And in few cases, I have to do a small extra code for particular workers.
To make it more clear, my "workers" are in fact access layers to a proprietary DB, each worker for a single DB version (and they are generated).
My current plan is to use something like FreeMaker to generate multiple Java source files, one for each DB version, which will have only different imports.
The topic to look into for you: generics
You can declare a class like
public class Whatever<T> {
which uses a T that allows for any reference type. You don't need to further "specialize" that T mandatorily. But of course: in this case you can only call methods from Object on instances of T.
If you want to call a more specific method, then there is no other way but somehow describing that specification. So in your case, the reasonable approach would be to introduce at least some core interfaces.
In other words: there is no "duck typing" in Java. You can't describe an object by only saying it has this or that method. You always need a type - and that must be either a class or an interface.
Duck typing isn't supported in Java. It can be approximated but you won't get the convenience or power you're used to in C++.
As options, consider:
Full-on reflection + working with Object - syntax will be terrible and the compiler won't help you with compilation checks.
Support a pre-known set of types and use some sort of static dispatching, e.g a big switch / if-else-if block, a type -> code map, etc. New types will force changing this code.
Code generation done during annotation processing - you may be able to automate the above static-dispatch approach, or be able to create a wrapper type to each supported type that does implement a common interface. The types need to be known during compilation, new types require recompilation.
EDIT - resources for code generation and annotation processing:
Annotation processing tutorial by #sockeqwe
JavaPoet, a clean code generation tool by Square
If you really don't have any way to get it done correctly with generics you may need to use reflection.
class A {
public String doIt() {
return "Done it!";
}
}
class B {
public Date doIt() {
return Calendar.getInstance().getTime();
}
}
interface I {
public Object doIt();
}
class IAdapter implements I {
private final Object it;
public IAdapter(Object it) {
this.it = it;
}
#Override
public Object doIt() {
// What class it it.
Class<?> itsClass = it.getClass();
// Peek at it's methods.
for (Method m : itsClass.getMethods()) {
// Correct method name.
if (m.getName().equals("doIt")) {
// Expose the method.
m.setAccessible(true);
try {
// Call it.
return m.invoke(it);
} catch (Exception e) {
throw new RuntimeException("`doIt` method invocation failed", e);
}
}
}
// No method of that name found.
throw new RuntimeException("Object does not have a `doIt` method");
}
}
public void test() throws Exception {
System.out.println("Hello world!");
Object a = new IAdapter(new A()).doIt();
Object b = new IAdapter(new B()).doIt();
System.out.println("a = "+a+" b = "+b);
}
You should, however, make every effort to solve this issue using normal type-safe Java such as Generics before using reflection.
In Java all your Workers must have a method DoSomething(someArgs), which doesn't necessarily imply that they extend the same base class, they could instead implement an interface Worker with such a method. For instance:
public interface Worker {
public Double DoSomething(String arg1, String arg2);
}
and then have different classes implement the Worker interface:
One implementation of Worker:
public class WorkerImplA implements Worker{
#Override
public Double DoSomething(String arg1, String arg2) {
return null; // do something and return meaningful outcome
}
}
Another implementatin of Worker:
public class WorkerImplB implements Worker{
#Override
public Double DoSomething(String arg1, String arg2) {
return null; // do something and return meaningful outcome
}
}
The different WorkerImpl classes do not need to extend the same common base class with this approach, and as of JavaSE 8 interfaces can have a default implementation in any method they define.
Using this approach Algorithm class would look like:
public class Algorithm {
private String arg1;
private String arg2;
public Algorithm(String arg1, String arg2){
this.arg1 = arg1;
this.arg2 = arg2;
}
public void Run(Worker worker){
worker.DoSomething(arg1, arg2);
}
}

Equivalent of Java's anonymous class in C#?

I am trying to port an SDK written in java to C#.
In this software there are many "handler" interfaces with several methods (for example: attemptSomethingHandler with success() and several different failure methods). This interface is then implemented and instantiated anonymously within the calling class and passed to the attemptSomething method of the SomethingModel class. This is an async method and has several places where it could fail or calls another method (passing on the handler). This way, the anonymous implementation of attemptSomethingHandler can reference private methods in the class that calls attemptSomething.
In C# it is not possible to anonymously implement an interface. I could explicitly implement a new class, but this implementation would be unique to this calling class and not used for anything else. More importantly, I would not be able to access the private methods in the calling class, which I need and do not want to make public.
Basically, I need to run different code from the calling class depending on what happens in the SomethingModel class methods.
I've been reading up on delegates but this would require passing as many delegates as there are methods in the handler interface (as far as I can tell).
What is the appropriate way to do this in C#? I feel like I'm missing out on a very common programming strategy. There simply must be an easy, clean way to structure and solve this problem.
Using delegates:
void AttemptSomethingAsync(Action onSuccess, Action<string> onError1, Action onError2 = null) {
// ...
}
// Call it using:
AttemptSomethingAsync(onSuccess: () => { Yes(); }, onError1: (msg) => { OhNo(msg); });
Or, using a class
class AttemptSomethingHandler {
Action OnSuccess;
Action<string> OnError1;
Action OnError2;
}
void AttemptSomethingAsync(AttemptSomethingHandler handler) {
// ...
}
// And you call it like
AttemptSomethingAsync(new AttemptSomethingHandler() {
OnSuccess = () => { Yes() };
});
Or events
public delegate void SuccessHandler();
public delegate void ErrorHandler(string msg);
class SomethingModel {
public event SuccessHandler OnSuccess;
public event ErrorHandler OnError1;
public void AttemptSomethingAsync() {
// ...
}
}
// Use it like
var model = new SomethingModel();
model.OnSuccess += Yes;
model.AttemptSomethingAsync();
private void Yes() {
}
In C#, we don't have anonymous types like Java per se. You can create an anonymous type which contains fields like so:
var myObject = new { Foo = "foo", Bar = 1, Quz = 4.2f }
However these cannot have methods placed in them and are only passable into methods by use of object or dynamic (as they have no type at compile-time, they are generated by the compiler AFAIK)
Instead in C# we use, as you said, delegates or lambdas.
If I understand your pickle correctly, you could implement a nested private class like so:
interface IMyInterface
{
void Foo();
}
class MyClass
{
public void Bar()
{
var obj = new MyInterface();
obj.Foo();
}
private class MyInterface : IMyInterface
{
public void Foo()
{
// stuff
}
}
}
Now MyClass can create an instance of MyInterface which implements IMyInterface. As commentors have mentioned, MyInterface can access members of MyClass (although you most certainly want to try and stick to using publicly accessible members of both types).
This encapsulates the "anonymous" class (using Java terms here to make it simpler) and also means that you could potentially return MyInterface as an IMyInterface and the rest of the software would be none the wiser. This is actually how some abstract factory patterns work.
Basically, I need to run different code from the calling class depending on what happens in the SomethingModel class methods.
This smells of heavy coupling. Oh dear!
It sounds to me like your particular problem could use refactoring. In C# you can use Events to solve this (note: Can, not should). Just have an Event for each "branch" point of your method. However I must say that this does make your solution harder to envisage and maintain.
However I suggest you architect your solution in a way such that you don't need such heavy coupling like that.
You could also try using a Pipeline model but I'm not sure how to implement that myself. I know that jetty (or is it Netty? the NIO for Java by JBOSS) certainly used a similar model.
You may find that throwing out some unit tests in order to test the expected functionality of your class will make it easier to architect your solution (TDD).
You can use nested classes to simulate anonymous classes, but in order to use nested classes in the same way as Java you will need to pass a reference to the outer class. In Java all nested and anonymous classes have this by default, and only static ones do not.
interface IMyInterface
{
void Foo();
}
class MyClass
{
public void Bar()
{
IMyInterface obj = new AnonymousAnalog(this);
obj.Foo();
}
private class AnonymousAnalog : IMyInterface
{
public void Foo(MyClass outerThis)
{
outerThis.privateFieldOnOuter;
outerThis.PrivateMethodOnOuter();
}
}
...
}

What is ducktyping in java terms? I thought it was a concept more native to dynamic scripting languages [duplicate]

I just recently heard of duck typing and I read the Wikipedia article about it, but I'm having a hard time translating the examples into Java, which would really help my understanding.
Would anyone be able to give a clear example of duck typing in Java and how I might possibly use it?
Java is by design not fit for duck typing. The way you might choose to do it is reflection:
public void doSomething(Object obj) throws Exception {
obj.getClass().getMethod("getName", new Class<?>[] {}).invoke(obj);
}
But I would advocate doing it in a dynamic language, such as Groovy, where it makes more sense:
class Duck {
quack() { println "I am a Duck" }
}
class Frog {
quack() { println "I am a Frog" }
}
quackers = [ new Duck(), new Frog() ]
for (q in quackers) {
q.quack()
}
Reference
See this blog post. It gives a very detailed account of how to use dynamic proxies to implement duck typing in Java.
In summary:
create an interface that represents the methods you want to use via duck typing
create a dynamic proxy that uses this interface and an implementation object that invokes methods of the interface on the underlying object by reflection (assuming the signatures match)
check this library:
interface MyInterface {
void foo();
int bar(int x, int y);
int baz(int x);
}
public class Delegate {
public int bar() {
return 42;
}
}
DuckPrxy duckProxy = new DuckPrxyImpl();
MyInterface prxy = duckProxy.makeProxy(MyInterface.class, new Delegate());
prxy.bar(2, 3); // Will return 42.
With an interface duck typing is simple using a Dynamic Proxy, you should match the method name and return type.
Java doesn't implement duck typing.
With java 8, you have 2 ways:
nº1: if you only need one method, use lambdas
static interface Action { public int act(); }
public int forEachAct(List<Action> actionlist) {
int total = 0;
for (Action a : actionList)
total += a.act();
}
public void example() {
List<Action> actionList = new ArrayList<>();
String example = "example";
actionList.add(example::length);
forEachAct(actionList);
}
nº2: Use anonymous classes (not very performance-wise, but in some non-critical parts it can be done)
static interface Action {
public int act();
public String describe();
}
public void example() {
List<Action> actionList = new ArrayList<>();
String example = "example";
actionList.add(new Action(){
public int act() { return example.length(); }
public String describe() { return "Action: " + example; }
});
}
I've written a utility class to dynamically create decorators for an object. You could use it for duck typing:
https://gist.github.com/stijnvanbael/5965616
Example:
interface Quacking {
void quack();
}
class Duck {
public void quack() { System.out.println("Quack!"); }
}
class Frog {
public void quack() { System.out.println("Ribbip!"); }
}
Quacking duck = Extenter.extend(new Duck()).as(Quacking.class);
Quacking frog = Extenter.extend(new Frog()).as(Quacking.class);
duck.quack();
frog.quack();
Output:
Quack!
Ribbip!
Typing in Java is nominal - compatibility is based on names. If you need an examples on how duck-typing (or structural typing) may look like in Java please look at this page: http://whiteoak.sourceforge.net/#Examples which provides examples for program written in Whiteoak: A Java-compatible language that also supports structural typing.
Typically, duck typing is used with dynamically typed languages. You would check at runtime for the existence of methods or properties that are required to fulfill your needs, regardless of inheritance hierarchies.
Other than using reflection, which would get ugly, the closest you can get is by using minimal interfaces that match the criteria of what you would need for duck typing. This blog post does a good job describing the concept. It loses much of the simplicity of duck typing in python or ruby or javascript, but its actually pretty good practice in Java if you're looking for a high level of reusability.
Nice definition:
Objects are polymorphic without being related by a common base class or interface.
Reference
Late to the party (as usual), but I wrote a quick class for doing some duck typing myself. See here.
It will only go to interfaces, but for a usage example:
interface Bird {
void fly();
}
interface Duck extends Bird {
void quack();
}
class PseudoDuck {
void fly() {
System.out.println("Flying");
}
void quack() {
System.out.println("Quacking");
}
}
class Tester {
#Test
void testDuckTyping() {
final Duck duck
= DuckTyper.duckType(new PseudoDuck(), Duck.class);
}
}
Supports default interface methods, parameters, checking Exception types are compatible and will check all methods of the PseudoDuck's class (including private). Haven't done any testing with generic interfaces yet though.

What's an example of duck typing in Java?

I just recently heard of duck typing and I read the Wikipedia article about it, but I'm having a hard time translating the examples into Java, which would really help my understanding.
Would anyone be able to give a clear example of duck typing in Java and how I might possibly use it?
Java is by design not fit for duck typing. The way you might choose to do it is reflection:
public void doSomething(Object obj) throws Exception {
obj.getClass().getMethod("getName", new Class<?>[] {}).invoke(obj);
}
But I would advocate doing it in a dynamic language, such as Groovy, where it makes more sense:
class Duck {
quack() { println "I am a Duck" }
}
class Frog {
quack() { println "I am a Frog" }
}
quackers = [ new Duck(), new Frog() ]
for (q in quackers) {
q.quack()
}
Reference
See this blog post. It gives a very detailed account of how to use dynamic proxies to implement duck typing in Java.
In summary:
create an interface that represents the methods you want to use via duck typing
create a dynamic proxy that uses this interface and an implementation object that invokes methods of the interface on the underlying object by reflection (assuming the signatures match)
check this library:
interface MyInterface {
void foo();
int bar(int x, int y);
int baz(int x);
}
public class Delegate {
public int bar() {
return 42;
}
}
DuckPrxy duckProxy = new DuckPrxyImpl();
MyInterface prxy = duckProxy.makeProxy(MyInterface.class, new Delegate());
prxy.bar(2, 3); // Will return 42.
With an interface duck typing is simple using a Dynamic Proxy, you should match the method name and return type.
Java doesn't implement duck typing.
With java 8, you have 2 ways:
nº1: if you only need one method, use lambdas
static interface Action { public int act(); }
public int forEachAct(List<Action> actionlist) {
int total = 0;
for (Action a : actionList)
total += a.act();
}
public void example() {
List<Action> actionList = new ArrayList<>();
String example = "example";
actionList.add(example::length);
forEachAct(actionList);
}
nº2: Use anonymous classes (not very performance-wise, but in some non-critical parts it can be done)
static interface Action {
public int act();
public String describe();
}
public void example() {
List<Action> actionList = new ArrayList<>();
String example = "example";
actionList.add(new Action(){
public int act() { return example.length(); }
public String describe() { return "Action: " + example; }
});
}
I've written a utility class to dynamically create decorators for an object. You could use it for duck typing:
https://gist.github.com/stijnvanbael/5965616
Example:
interface Quacking {
void quack();
}
class Duck {
public void quack() { System.out.println("Quack!"); }
}
class Frog {
public void quack() { System.out.println("Ribbip!"); }
}
Quacking duck = Extenter.extend(new Duck()).as(Quacking.class);
Quacking frog = Extenter.extend(new Frog()).as(Quacking.class);
duck.quack();
frog.quack();
Output:
Quack!
Ribbip!
Typing in Java is nominal - compatibility is based on names. If you need an examples on how duck-typing (or structural typing) may look like in Java please look at this page: http://whiteoak.sourceforge.net/#Examples which provides examples for program written in Whiteoak: A Java-compatible language that also supports structural typing.
Typically, duck typing is used with dynamically typed languages. You would check at runtime for the existence of methods or properties that are required to fulfill your needs, regardless of inheritance hierarchies.
Other than using reflection, which would get ugly, the closest you can get is by using minimal interfaces that match the criteria of what you would need for duck typing. This blog post does a good job describing the concept. It loses much of the simplicity of duck typing in python or ruby or javascript, but its actually pretty good practice in Java if you're looking for a high level of reusability.
Nice definition:
Objects are polymorphic without being related by a common base class or interface.
Reference
Late to the party (as usual), but I wrote a quick class for doing some duck typing myself. See here.
It will only go to interfaces, but for a usage example:
interface Bird {
void fly();
}
interface Duck extends Bird {
void quack();
}
class PseudoDuck {
void fly() {
System.out.println("Flying");
}
void quack() {
System.out.println("Quacking");
}
}
class Tester {
#Test
void testDuckTyping() {
final Duck duck
= DuckTyper.duckType(new PseudoDuck(), Duck.class);
}
}
Supports default interface methods, parameters, checking Exception types are compatible and will check all methods of the PseudoDuck's class (including private). Haven't done any testing with generic interfaces yet though.

Categories

Resources