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
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 need to do a lot of different preprocessing of some text data, the preprocessing consists of several simple regex functions all written in class Filters that all take in a String and returns the formatted String. Up until now, in the different classes that needed some preprocessing, I created a new function where I had a bunch of calls to Filters, they would look something like this:
private static String filter(String text) {
text = Filters.removeURL(text);
text = Filters.removeEmoticons(text);
text = Filters.removeRepeatedWhitespace(text);
....
return text;
}
Since this is very repetitive (I would call about 90% same functions, but 2-3 would be different for each class), I wonder if there are some better ways of doing this, in Python you can for example put function in a list and iterate over that, calling each function, I realize this is not possible in Java, so what is the best way of doing this in Java?
I was thinking of maybe defining an enum with a value for each function and then call a main function in Filters with array of enums with the functions I want to run, something like this:
enum Filter {
REMOVE_URL, REMOVE_EMOTICONS, REMOVE_REPEATED_WHITESPACE
}
public static String filter(String text, Filter... filters) {
for(Filter filter: filters) {
switch (filter) {
case REMOVE_URL:
text = removeURL(text);
break;
case REMOVE_EMOTICONS:
text = removeEmoticons(text);
break;
}
}
return text;
}
And then instead of defining functions like shown at the top, I could instead simply call:
filter("some text", Filter.REMOVE_URL, Filter.REMOVE_EMOTICONS, Filter.REMOVE_REPEATED_WHITESPACE);
Are there any better ways to go about this?
Given that you already implemented your Filters utility class you can easily define a list of filter functions
List<Function<String,String>> filterList = new ArrayList<>();
filterList.add(Filters::removeUrl);
filterList.add(Filters::removeRepeatedWhitespace);
...
and then evaluate:
String text = ...
for (Function<String,String> f : filterList)
text = f.apply(text);
A variation of this, even easier to handle:
Define
public static String filter(String text, Function<String,String>... filters)
{
for (Function<String,String> f : filters)
text = f.apply(text);
return text;
}
and then use
String text = ...
text = filter(text, Filters::removeUrl, Filters::removeRepeatedWhitespace);
You could do this in Java 8 pretty easily as #tobias_k said, but even without that you could do something like this:
public class FunctionExample {
public interface FilterFunction {
String apply(String text);
}
public static class RemoveSpaces implements FilterFunction {
public String apply(String text) {
return text.replaceAll("\\s+", "");
}
}
public static class LowerCase implements FilterFunction {
public String apply(String text) {
return text.toLowerCase();
}
}
static String filter(String text, FilterFunction...filters) {
for (FilterFunction fn : filters) {
text = fn.apply(text);
}
return text;
}
static FilterFunction LOWERCASE_FILTER = new LowerCase();
static FilterFunction REMOVE_SPACES_FILTER = new RemoveSpaces();
public static void main(String[] args) {
String s = "Some Text";
System.out.println(filter(s, LOWERCASE_FILTER, REMOVE_SPACES_FILTER));
}
}
Another way would be to add a method to your enum Filter and implement that method for each of the enum literals. This will also work with earlier versions of Java. This is closest to your current code, and has the effect that you have a defined number of possible filters.
enum Filter {
TRIM {
public String apply(String s) {
return s.trim();
}
},
UPPERCASE {
public String apply(String s) {
return s.toUpperCase();
}
};
public abstract String apply(String s);
}
public static String applyAll(String s, Filter... filters) {
for (Filter f : filters) {
s = f.apply(s);
}
return s;
}
public static void main(String[] args) {
String s = " Hello World ";
System.out.println(applyAll(s, Filter.TRIM, Filter.UPPERCASE));
}
However, if you are using Java 8 you can make your code much more flexible by just using a list of Function<String, String> instead. If you don't like writing Function<String, String> all the time, you could also define your own interface, extending it:
interface Filter extends Function<String, String> {}
You can then define those functions in different ways: With method references, single- and multi-line lambda expressions, anonymous classes, or construct them from other functions:
Filter TRIM = String::trim; // method reference
Filter UPPERCASE = s -> s.toUpperCase(); // one-line lambda
Filter DO_STUFF = (String s) -> { // multi-line lambda
// do more complex stuff
return s + s;
};
Filter MORE_STUFF = new Filter() { // anonymous inner class
// in case you need internal state
public String apply(String s) {
// even more complex calculations
return s.replace("foo", "bar");
};
};
Function<String, String> TRIM_UPPER = TRIM.andThen(UPPERCASE); // chain functions
You can then pass those to the applyAll function just as the enums and apply them one after the other in a loop.
String activityState = "resume";
DebugLog(activityState)
void DebugLog(String obj1) {}
How to make the DebugLog to print like this:
activityState : resume
I used to write many print statement as logs at many places while debugging. I will write statements like
System.out.println("activityState : " + activityState);
I want a method to print the variable name and variable value. In C++, it can be done like the below:
#define dbg(x) cout<< #x <<" --> " << x << endl ;
Is there any way to do this?
Thanks in advance.
There's no direct solution to get the variable name.
However, in a context where you have many fields and don't want to manually print their state, you can use reflection.
Here's a quick example:
class MyPojo {
public static void main(String[] args) {
System.out.println(new MyPojo());
}
int i = 1;
String s = "foo";
#Override
public String toString() {
StringBuilder result = new StringBuilder();
for (Field f: getClass().getDeclaredFields()) {
try {
result
.append(f.getName())
.append(" : ")
.append(f.get(this))
.append(System.getProperty("line.separator"));
}
catch (IllegalStateException ise) {
result
.append(f.getName())
.append(" : ")
.append("[cannot retrieve value]")
.append(System.getProperty("line.separator"));
}
// nope
catch (IllegalAccessException iae) {}
}
return result.toString();
}
}
Output
i : 1
s : foo
You can use java Reflection to get the variable name and the value. Here's an example code;
public class Example{
String activityState = "resume";
public static void main(String[] args) {
Example example = new Example();
Class<?> c = example.getClass();
Field field = c.getDeclaredField("activityState");
System.out.println(field.getName());
System.out.println(field.get(example));
}
}
Since this is for debugging you could use instrumentation with aspectj, your code remains clean from the the debugging output statements and you can waeve the aspect as needed.
Define a set(FieldPattern) point cut to catch all field assignements (join points)
public aspect TestAssignmentAspect {
pointcut assigmentPointCut() : set(* *);
after() : assigmentPointCut() {
System.out.printf("%s = %s%n", thisJoinPoint.getSignature().getName(),
String.valueOf(Arrays.toString(thisJoinPoint.getArgs())));
}
}
Here is Test class
public class Test {
public static String activityState = "stopped";
public static void main(String[] args) {
activityState = "start";
doSomething();
activityState = "pause";
doSomeOtherthing();
activityState = "resume";
System.out.printf("the end!%n");
}
private static void doSomeOtherthing() {
System.out.printf("doing some other thing...%n");
}
private static void doSomething() {
System.out.printf("doing something...%n");
}
}
If you run this example with the aspect weaved the output will be
activityState = [stopped]
activityState = [start]
doing something...
activityState = [pause]
doing some other thing...
activityState = [resume]
the end!
Explanation
pointcut assigmentPointCut() : set(* *);
set point cut to catch assignments, the point joins, to any variable with any name, could also in the example be
pointcut assigmentPointCut() : set(String activityState);
The advice, the desired behavior when the given point cut matches
after() : assigmentPointCut() { ... }
Informations about the point join can be accessed using the special reference thisJoinPoint.
This could well be a stupid question, but I'm new to Java, so...
I've currently got some code where currently this is being used
clazz.asSubclass(asSubclassOfClass).getConstructor().newInstance()
I need to pass some arguments to the contructort so I want to change it to: clazz.asSubclass(asSubclassOfClass).getConstructor(params).newInstance(args)
What I don't understand is what I need to pass in as params and what I need to pass in as args.
Let's say I wanted to pass in a String "howdy" and some object of type XYZ called XyzObj in. How would I specify that? WHat would I pass as params and what would I pass as args?
In Java this is called Reflection.
Assuming the class has this constructor, otherwise you will get a NoSuchMethod exception I believe.
clazz.asSubclass(asSubclassOfClass)
.getConstructor(String.class,XYZ.class)
.newInstance("howdy",XyzObj);
Since you are new to Java, let me give you an easier so that you can understand what's going on under the hood when you do this.
Assume you have the following class:
public class ParentClazz{
String someVar;
public ParentClazz(){
someVar="test";
}
public ParentClazz(String someVar){
System.out.println("I have been invoked");
this.someVar=someVar;
}
}
Then you have the following main method:
public static void main(String[] args) throws ParseException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
ParentClazz.class.asSubclass(ParentClazz.class).getConstructor(String.class).newInstance("howdy");
}
If you run this you will notice the console output print message - I have been invoked. This means that using reflection you have invoked the constructor of ParentClazz.
You can do the same thing if the scenario allows you is by using standard object creation process:
ParentClazz clazz = new ParentClazz("howdy");
Hope this helps you understand it.
Here is an example of creating classes without the new keyword.
The classes take other classes both primitives and Objects as their parameters.
The example also shows the instance of a subclass and a Parent class being created
public class ConstructorInstantiateWithoutNew
{
#SuppressWarnings("rawtypes")
public static void main( String [] args )
{
Class<Drinker> clazz_drinker = Drinker.class;
Class [] paramTypes = { Fizz.class, Colour.class, int.class };
Object [] paramValues = { new Fizz(), new Colour(), new Integer(10) };
Class<Drunk> clazz_drunk = Drunk.class;
Class [] paramTypesSub = { Fizz.class, Colour.class, int.class, boolean.class };
Object [] paramValuesSub = { new Fizz(), new Colour(), new Integer(10), true };
try
{
Drinker drinker = clazz_drinker.getConstructor( paramTypes ).newInstance( paramValues );
drinker.drink();
Drunk drunk = clazz_drunk.getConstructor(paramTypesSub).newInstance(paramValuesSub);
drunk.drink();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
class Drinker
{
int n;
public Drinker( Fizz f, Colour c, int n)
{
this.n = n;
}
public void drink()
{
System.out.println( "Dad drank " + (n*10) + " ml");
}
}
class Drunk extends Drinker
{
boolean trouble;
public Drunk(Fizz f, Colour c, int n, boolean inDogHouse)
{
super(f,c,n);
trouble = inDogHouse;
}
public void drink()
{
System.out.println(
"Dad is Grounded: " + trouble +
" as he drank over "+
(n*10) + " ml");
}
}
class Fizz {} class Colour {}
Hope this is useful
Kind regards
Naresh Maharaj
clazz.asSubclass(asSubclassOfClass)
.getConstructor(String.class, XYZ.class)
.newInstance("howdy", XyzObj)
Which assumes that the constructor args are in the specified order
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