In C# you can define delegates anonymously (even though they are nothing more than syntactic sugar). For example, I can do this:
public string DoSomething(Func<string, string> someDelegate)
{
// Do something involving someDelegate(string s)
}
DoSomething(delegate(string s){ return s += "asd"; });
DoSomething(delegate(string s){ return s.Reverse(); });
Is it possible to pass code like this in Java? I'm using the processing framework, which has a quite old version of Java (it doesn't have generics).
Pre Java 8:
The closest Java has to delegates are single method interfaces. You could use an anonymous inner class.
interface StringFunc {
String func(String s);
}
void doSomething(StringFunc funk) {
System.out.println(funk.func("whatever"));
}
doSomething(new StringFunc() {
public String func(String s) {
return s + "asd";
}
});
doSomething(new StringFunc() {
public String func(String s) {
return new StringBuffer(s).reverse().toString();
}
});
Java 8 and above:
Java 8 adds lambda expressions to the language.
doSomething((t) -> t + "asd");
doSomething((t) -> new StringBuilder(t).reverse().toString());
Not exactly like this but Java has something similar.
It's called anonymous inner classes.
Let me give you an example:
DoSomething(new Runnable() {
public void run() {
// "delegate" body
}
});
It's a little more verbose and requires an interface to implement,
but other than that it's pretty much the same thing
Your example would look like this in Java, using anomymous inner classes:
interface Func {
String execute(String s);
}
public String doSomething(Func someDelegate) {
// Do something involving someDelegate.execute(String s)
}
doSomething(new Func() { public String execute(String s) { return s + "asd"; } });
doSomething(new Func() { public String execute(String s) { return new StringBuilder(s).reverse().toString(); } } });
Is it possible to pass code like this
in Java? I'm using the processing
framework, which has a quite old
version of Java (it doesn't have
generics).
Since the question asked about the Processing-specific answer, there is no direct equivalent. But Processing uses the Java 1.4 language level, and Java 1.1 introduced anonymous inner classes, which are a rough approximation.
For example :
public class Delegate
{
interface Func
{
void execute(String s);
}
public static void doSomething(Func someDelegate) {
someDelegate.execute("123");
}
public static void main(String [] args)
{
Func someFuncImplementation = new Func()
{
#Override
public void execute(String s) {
System.out.println("Bla Bla :" + s);
}
};
Func someOtherFuncImplementation = new Func()
{
#Override
public void execute(String s) {
System.out.println("Foo Bar:" + s);
}
};
doSomething(someFuncImplementation);
doSomething(someOtherFuncImplementation);
}
}
Output :
Bla Bla :123
Foo Bar:123
You have all forgotten here that a C# delegate first of all - is thread safe.
These examples are just for a single thread App..
Most of the contemporary Apps are written on multithreaded concept..
So no one answer is the answer.
There is not an equivalent in Java
Related
I'm running SonarLint 3.4 and Oracle JDK 8. SonarLint is giving me this error:
Anonymous inner classes containing only one method should become lambdas (squid:S1604)
The interface, which I don't have control over, is setup like this:
public interface Interface {
static String staticMethodOne() {
return "abc";
}
default String methodOne(String input) {
return "one: " + input;
}
default String methodTwo(String input) {
return "two: " + input;
}
}
This is the code that generates the error:
public class Main {
public static void main(String[] args) {
callMethodOne(
new Interface() {
#Override
public String methodOne(String input) {
return ("override: " + input);
}
}
);
}
private static void callMethodOne(Interface instance) {
System.out.println(instance.methodOne("test"));
}
}
Since "Interface" is not a functional interface I don't see a way to replace it with a lambda. Is this a bug in SonarLint or am I missing something?
Confirmed as a bug in SonarJava; time to wait for the next SonarLint update.
https://jira.sonarsource.com/browse/SONARJAVA-2654
I have these two methods
private void saveBaseLineLatency(E2EResultShort e2EResultShort) {
LatencyHistogram latencyHistogram = getLatencyHistogram(e2EResultShort);
latencyDrillDownRepository.saveBaseLine(latencyHistogram);
saveLatencyTable(latencyHistogram);
}
private void saveFreshTestLatency(E2EResultShort e2EResultShort) {
System.out.println("log: before saveLatencyHistogram");
LatencyHistogram latencyHistogram = getLatencyHistogram(e2EResultShort);
latencyDrillDownRepository.save(latencyHistogram);
saveLatencyTable(latencyHistogram);
}
How can I refactor out their common code?
I thought to use Callable but its call() is parameterless.
Consumer is the interface you want. It's part of the new java.util.function package in Java 8, so this won't work if you're on an older version of Java. (The package also has a number of similar other interfaces, like a BiConsumer that takes two arguments, and interfaces for consuming various primitive types as well.)
So, your helper method would be something like:
private void doLatencyOperation (E2EResultShort newThing, Consumer<LatencyHistogram> consumer) {
LatencyHistogram lh = getLatencyHistogram(newThing);
consumer.accept(lh);
saveLatencyTable(lh);
}
and you could call it thusly
private void saveBaseLineLatency(E2EResultShort e2EResultShort) {
doLatencyOperation(e2EResultShort, (lh) -> latencyDrillDownRepository.saveBaseLine(lh));
}
Create an abstract class and move all the common code there.
public abstract class MyClass{
public MyClass(E2EResultShort result, latencyDrillDownRepository){
this.result = result;
}
public void execute() {
LatencyHistogram latencyHistogram = getLatencyHistogram(e2EResultShort);
callMe(latencyHistogram, latencyDrillDownRepository);
saveLatencyTable(latencyHistogram);
}
public abstract void callMe(LatencyHistogram latencyHistogram, latencyDrillDownRepository);
}`
Now in your method, create concrete MyClass:
private void saveFreshTestLatency(E2EResultShort e2EResultShort) {
System.out.println("log: before saveLatencyHistogram");
MyClass myClass = new MyClass(e2EResultShort, latencyDrillDownRepository){
public void callMe(LatencyHistogram latencyHistogram, latencyDrillDownRepository){
latencyDrillDownRepository.save(latencyHistogram);
}
}
myClass.execute();
}
While reading online, I came across the following:
public interface UnaryFunction<T>
{
T apply(T arg);
}
.......
private static UnaryFuntion<Object> ID_FUNC = new UnaryFunction<Object>
{
Object apply(Object arg)
{
return arg;
}
};
public static <T> UnaryFunction<T> idFunction()
{
return (UnaryFunction<T>) ID_FUNC;
}
In main:
public static void main(String[] args)
{
String[] strings = {"Peter", "Paul", "Mary"};
UnaryFunction<String> names = idFunction();
for(String s : strings)
{
System.out.println(names.apply(s));
}
Number[] numbers = {1, 2.0, 3L};
UnaryFunction<Number> nums = idFunction();
for(Number n : numbers)
{
System.out.println(nums.apply(n));
}
}
My question is, why do we need a generic interface here?
Would simply the following suffice:
public interface UnaryFunction
{
Object apply(Object arg); //Object as return type and argument type, instead.
}
? What is the need here to use generics?
And, what is actually a generic singleton factory? What is it good for?
Thanks.
The generic singleton factory is the idFunction in your example. Without it you would have a choice between two ugly alternatives, either require a cast wherever you use it, like this:
public class ExampleWithoutGenericSingletonFactory {
static UnaryFunction<Object> ID_FUNC = new UnaryFunction<Object>() {
public Object apply(Object arg) {
return arg;
}
};
public static void main(String[] args) {
BigDecimal b = new BigDecimal("1234.1241234");
BigDecimal b1 = (BigDecimal)(ID_FUNC.apply(b)); // have to cast here >_<
System.out.println("engineeringstring val of b1 = "
+ b1.toEngineeringString());
}
}
or make separate implementations for every type you want to support:
public static UnaryFunction<String> ID_FUNC_STRING = new UnaryFunction<String>() {
public String apply(String arg) {
return arg;
}
};
public static UnaryFunction<Number> ID_FUNC_NUM = new UnaryFunction<Number>() {
public Number apply(Number arg) {
return arg;
}
};
public static UnaryFunction<BigDecimal> ID_FUNC_DECIMAL = new UnaryFunction<BigDecimal>() {
public Number apply(BigDecimal arg) {
return arg;
}
};
giving you some ugly verbose cut-n-pasted code with a different name for every type that you have to keep straight. But since you know it's a pure function and the types get erased, you can have only one implementation (ID_FUNC) and have the singleton factory idFunction return it.
You would use this for cases where you have one function implementation that you want to be able to specify different types on, where the implementation is stateless.
The example could be better, since it only calls toString on the objects returned from the function call there's no demonstrated benefit from the factory. If the example showed using type-specific methods on the objects returned then the benefit might be more apparent.
An unchecked cast warning comes up when you do this, but it's safe to suppress it (which is what Joshua Bloch advises).
I see about decorator example in Python:
def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
#makebold
#makeitalic
def hello():
return "hello world"
print hello() ## returns <b><i>hello world</i></b>
And got some curious how it can be implement in Java, so I search and got some example using Decorator Design Pattern.
public class Main {
public static void main(String[] args) {
Wrapper word = new BoldWrapper(new ItalicWrapper());
// display <b><i>hello world</i></b>
System.out.println(word.make("Hello World"));
}
}
public interface Wrapper {
public String make(String str);
}
public class BoldWrapper implements Wrapper {
private Wrapper wrapper;
public BoldWrapper() {
}
public BoldWrapper(Wrapper wrapper) {
this.wrapper = wrapper;
}
#Override
public String make(String str) {
if(wrapper != null) {
str = wrapper.make(str);
}
return "<b>" + str + "</b>";
}
}
public class ItalicWrapper implements Wrapper {
private Wrapper wrapper;
public ItalicWrapper() {
}
public ItalicWrapper(Wrapper wrapper) {
this.wrapper = wrapper;
}
#Override
public String make(String str) {
if(wrapper != null) {
str = wrapper.make(str);
}
return "<i>" + str + "</i>";
}
}
How do I make this like the Python example above using a Java Annotation like this one:
public class Main {
public static void main(String[] args) {
#BoldWrapper
#ItalicWrapper
String str = "Hello World";
// Display <b><i>Hello World</i></b>
}
}
public #interface BoldWrapper {
public void wrap() default "<b>" + str + "</b>";
}
public #interface ItalicWrapper {
public void wrap() default "<i>" + str + "</i>";
}
I got some problem when I tried to make the sample, the problem is I don't know how I can pass the str value from the main method to the BoldWrapper and ItalicWrapper so it can concatenate and how to return it, so the main method can display the result that has been concatenate.
Please advise if there is something wrong with my understanding of annotation.
If you are particularly interested in doing this kind of stuff with annotations (you don't have to really):
This example should get you started:
public class AnnotationTest
{
#Target( ElementType.METHOD )
#Retention( RetentionPolicy.RUNTIME )
public static #interface TagWrapper
{
public String[] value() default {};
}
public static interface TextFragment
{
public String getText();
}
public static class TagWrapperProcessor
{
public static String getWrapperTextFragment( TextFragment fragment )
{
try
{
Method getText = fragment.getClass().getMethod( "getText" );
TagWrapper tagWrapper = getText.getAnnotation( TagWrapper.class );
String formatString = "<%s>%s</%s>";
String result = ( String ) getText.invoke( fragment );
for ( String tag : tagWrapper.value() )
{
result = String.format( formatString, tag, result, tag );
}
return result;
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
}
}
public static class BoldItalicFragment implements TextFragment
{
private String _text;
public BoldItalicFragment( String text )
{
_text = text;
}
#Override
#TagWrapper(
{
"b", "i"
} )
public String getText()
{
return _text;
}
}
#Test
public void testStuff()
{
System.out.println( TagWrapperProcessor.getWrapperTextFragment( new BoldItalicFragment( "Hello, World!" ) ) ); // prints: <i><b>Hello, World!</b></i>
}
}
This is late but I think it may help the other people. From Java 8 with Function interface, we can write something close to python decorator like this:
Function<Function<String, String>, Function<String, String>> makebold = func -> input -> "<b>" + func.apply(input) + "</b>";
Function<Function<String, String>, Function<String, String>> makeitalic = func -> input -> "<i>" + func.apply(input) + "</i>";
Function<String, String> helloWorld = input -> "hello world";
System.out.println(makebold.apply(makeitalic.apply(helloWorld)).apply("")); // <b><i>hello world</i></b>
1) The link you cited is a good one - it does justice to the "Decorator Pattern" with respect to Java. "Design Patterns" themselves, of course, are independent of any particular OO language:
http://en.wikipedia.org/wiki/Design_Patterns
2) Here is another good link:
When to use the decorator pattern
In Java, a classical example of the decorator pattern is the Java I/O Streams implementation.
FileReader frdr = new FileReader(filename);
LineNumberReader lrdr = new LineNumberReader(frdr);
4) So yes, the "decorator pattern" is a good candidate for this problem.
Personally, I would prefer this kind of solution:
String myHtml =
new BoldText (
new ItalicText (
new HtmlText ("See spot run")));
5) However annotations are also an option. For example:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/annotations.html
Python decorators very like java annotation, but that are very different principle.
Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.
But you can prosessing class file with bytecode enhancement. I make a simple project for implementing that approach. It using javassist processing class file after building. It searching methods with specified annotation in classes. And add bridge methods for calling between wrapped method and original method. It look like, calling bridgeMethod() -> wrapperMethod() -> originalMethod(). Your can reference from https://github.com/eshizhan/funcwraps.
Although this doesn't resolve how to use annotations as you wanted, rather than using the "decorator design", I could propose you use the "builder design" if it suits better to your needs (it seems like so).
Quick usage example:
public class BuilderPatternExample {
public static void main(String args[]) {
//Creating object using Builder pattern in java
Cake whiteCake = new Cake.Builder()
.sugar(1)
.butter(0.5)
.eggs(2)
.vanilla(2)
.flour(1.5)
.bakingPowder(0.75)
.milk(0.5)
.build();
//Cake is ready to eat :)
System.out.println(whiteCake);
}
}
Output:
Cake{sugar=0.75, butter=0.5, eggs=2, vanila=2, flour=1.5, bakingpowder=0.0, milk=0.5, cherry=0}
For full implementation and a very good explanation, please check
http://javarevisited.blogspot.mx/2012/06/builder-design-pattern-in-java-example.html
I'm trying to define a class (or set of classes which implement the same interface) that will behave as a loosely typed object (like JavaScript). They can hold any sort of data and operations on them depend on the underlying type.
I have it working in three different ways but none seem ideal. These test versions only allow strings and integers and the only operation is add. Adding integers results in the sum of the integer values, adding strings concatenates the strings and adding an integer to a string converts the integer to a string and concatenates it with the string. The final version will have more types (Doubles, Arrays, JavaScript-like objects where new properties can be added dynamically) and more operations.
Way 1:
public interface DynObject1 {
#Override public String toString();
public DynObject1 add(DynObject1 d);
public DynObject1 addTo(DynInteger1 d);
public DynObject1 addTo(DynString1 d);
}
public class DynInteger1 implements DynObject1 {
private int value;
public DynInteger1(int v) {
value = v;
}
#Override
public String toString() {
return Integer.toString(value);
}
public DynObject1 add(DynObject1 d) {
return d.addTo(this);
}
public DynObject1 addTo(DynInteger1 d) {
return new DynInteger1(d.value + value);
}
public DynObject1 addTo(DynString1 d)
{
return new DynString1(d.toString()+Integer.toString(value));
}
}
...and similar for DynString1
Way 2:
public interface DynObject2 {
#Override public String toString();
public DynObject2 add(DynObject2 d);
}
public class DynInteger2 implements DynObject2 {
private int value;
public DynInteger2(int v) {
value = v;
}
#Override
public String toString() {
return Integer.toString(value);
}
public DynObject2 add(DynObject2 d) {
Class c = d.getClass();
if(c==DynInteger2.class)
{
return new DynInteger2(value + ((DynInteger2)d).value);
}
else
{
return new DynString2(toString() + d.toString());
}
}
}
...and similar for DynString2
Way 3:
public class DynObject3 {
private enum ObjectType {
Integer,
String
};
Object value;
ObjectType type;
public DynObject3(Integer v) {
value = v;
type = ObjectType.Integer;
}
public DynObject3(String v) {
value = v;
type = ObjectType.String;
}
#Override
public String toString() {
return value.toString();
}
public DynObject3 add(DynObject3 d)
{
if(type==ObjectType.Integer && d.type==ObjectType.Integer)
{
return new DynObject3(Integer.valueOf(((Integer)value).intValue()+((Integer)value).intValue()));
}
else
{
return new DynObject3(value.toString()+d.value.toString());
}
}
}
With the if-else logic I could use value.getClass()==Integer.class instead of storing the type but with more types I'd change this to use a switch statement and Java doesn't allow switch to use Classes.
Anyway... My question is what is the best way to go about something thike this?
What you are trying to do is called double dispatch. You want the method called to depend both on the runtime type of the object it's called on, and on the runtime type of its argument.
Java and other C derivatives support single dispatch only, which is why you need a kludge like the visitor pattern you used in option 1. This is the common way of implementing it. I would prefer this method because it uses no reflection. Furthermore, it allows you to keep each case in its own method, without needing a big "switchboard" method to do the dispatching.
I'd choose the second option, with the third, I'd better be using generics so you don't rely on that Enum. And with the first option you could be implementing methods for the rest of your life. Anyways you could use "instanceof" operator for Class matching.