Variable functions in Java - java

Is it possible through some method to assign a function to a variable in Java, like in PHP or JavaScript?
...Or does this area works on a different way when it comes to Java?

In Java you have Method and MethodHandles which can invoke a method via reflection but that is not supported in the language yet.
In Java 8, you will be able to use references to methods.

In today's java, no you can't.
The nearest you have is the interface : you don't store a function but the implementation of an interface defining the wanted function.
A typical example is the implementation of the Comparator interface :
Comparator<ProductSearchResult> c = new Comparator<ProductSearchResult>() {
public int compare(ProductSearchResult result1, ProductSearchResult result2) {
return result1.product.getRsId().compareTo(result2.product.getRsId());
}
};
Collections.sort(groupResults, c); // I pass a function, wrapped in my Comparator implementation

The nearest you have are inner classes combined with interfaces. These can carry not only one but many functions (methods) that can be delegated back to the master class methods if preferred. But this solution may easily be too heavyweight:
class Main {
interface X {
void doX();
}
class Ref1 implements X {
void doX() { doA(); };
}
class Ref2 implements X {
void doX() { doB(); };
}
void doA() { };
void doB() { };
void demo() {
X x = new Ref1();
x.doX();
}
}

This simulates something similar to Lambdas ... (you'll need a little more casting if you use anything other than Strings, but I'm keeping the example brief) ...
public class MyTest {
public static void main(String[] args) {
Lambda l = new Lambda() { public Object func(Object x)
{ return "Hello " + x; }
};
System.out.println(l.func("Bob"));
System.out.println(nowTryFromMethod(l));
System.out.println((new Lambda() { public Object func(Object x)
{ return "Goodbye " + x; }
}).func("Harry"));
}
private static Object nowTryFromMethod(Lambda l) {
return l.func("Jerry");
}
}
class Lambda {
public Object func(Object x) { return null; }
}
Output:
Hello Bob
Hello Jerry
Goodbye Harry
Update
Java supports reference to functions which is called Lambda from version 1.8

Java does NOT support that.
However, you can do that in JVM-Languages very comfortably, e.g. in Groovy.
Or you take a look at the command-pattern.

Related

How does the 'this' keyword play a role in overloading? [duplicate]

I have a collection (or list or array list) in which I want to put both String values and double values. I decided to make it a collection of objects and using overloading ond polymorphism, but I did something wrong.
I run a little test:
public class OOP {
void prova(Object o){
System.out.println("object");
}
void prova(Integer i){
System.out.println("integer");
}
void prova(String s){
System.out.println("string");
}
void test(){
Object o = new String(" ");
this.prova(o); // Prints 'object'!!! Why?!?!?
}
public static void main(String[] args) {
OOP oop = new OOP();
oop.test(); // Prints 'object'!!! Why?!?!?
}
}
In the test seems like the argument type is decided at compile time and not at runtime. Why is that?
This question is related to:
Polymorphism vs Overriding vs Overloading
Try to describe polymorphism as easy as you can
EDIT:
Ok the method to be called is decided at compile time. Is there a workaround to avoid using the instanceof operator?
This post seconds voo's answer, and gives details about/alternatives to late binding.
General JVMs only use single dispatch: the runtime type is only considered for the receiver object; for the method's parameters, the static type is considered. An efficient implementation with optimizations is quite easy using method tables (which are similar to C++'s virtual tables). You can find details e.g. in the HotSpot Wiki.
If you want multiple dispatch for your parameters, take a look at
groovy. But to my latest knowledge, that has an outdated, slow multiple dispatch implementation (see e.g. this performance comparison), e.g. without caching.
clojure, but that is quite different to Java.
MultiJava, which offers multiple dispatch for Java. Additionally, you can use
this.resend(...) instead of super(...) to invoke the most-specific overridden method of the enclosing method;
value dispatching (code example below).
If you want to stick with Java, you can
redesign your application by moving overloaded methods over a finer grained class hierarchy. An example is given in Josh Bloch's Effective Java, Item 41 (Use overloading judiciously);
use some design patterns, such as Strategy, Visitor, Observer. These can often solve the same problems as multiple dispatch (i.e. in those situations you have trivial solutions for those patterns using multiple dispatch).
Value dispatching:
class C {
static final int INITIALIZED = 0;
static final int RUNNING = 1;
static final int STOPPED = 2;
void m(int i) {
// the default method
}
void m(int##INITIALIZED i) {
// handle the case when we're in the initialized `state'
}
void m(int##RUNNING i) {
// handle the case when we're in the running `state'
}
void m(int##STOPPED i) {
// handle the case when we're in the stopped `state'
}
}
What you want is double or more general multiple dispatch, something that is actually implemented in other languages (common lisp comes to mind)
Presumably the main reason java doesn't have it, is because it comes at a performance penalty because overload resolution has to be done at runtime and not compile time. The usual way around this is the visitor pattern - pretty ugly, but that's how it is.
Old question but no answer provides a concrete solution in Java to solve the issue in a clean way.
In fact, not easy but very interesting question. Here is my contribution.
Ok the method to be called is decided at compile time. Is there a
workaround to avoid using the instanceof operator?
As said in the excellent #DaveFar answer, Java supports only the single-dispatch method.
In this dispatching mode, the compiler bounds the method to invoke as soon as the compilation by relying on the declared types of the parameters and not their runtime types.
I have a collection (or list or array list) in which I want to put
both String values and double values.
To solve the answer in a clean way and use a double dispatch, we have to bring abstraction for the manipulated data.
Why ?
Here a naive visitor approach to illustrate the issue :
public class DisplayVisitor {
void visit(Object o) {
System.out.println("object"));
}
void visit(Integer i) {
System.out.println("integer");
}
void visit(String s) {
System.out.println("string"));
}
}
Now, question : how visited classes may invoke the visit() method ?
The second dispatch of the double dispatch implementation relies on the "this" context of the class that accepts to be visited.
So we need to have a accept() method in Integer, String and Object classes to perform this second dispatch :
public void accept(DisplayVisitor visitor){
visitor.visit(this);
}
But impossible ! Visited classes are built-in classes : String, Integer, Object.
So we have no way to add this method.
And anyway, we don't want to add that.
So to implement the double dispatch, we have to be able to modify the classes that we want to pass as parameter in the second dispatch.
So instead of manipulating Object and List<Object> as declared type, we will manipulate Foo and List<Foo> where the Foo class is a wrapper holding the user value.
Here is the Foo interface :
public interface Foo {
void accept(DisplayVisitor v);
Object getValue();
}
getValue() returns the user value.
It specifies Object as return type but Java supports covariance returns (since the 1.5 version), so we could define a more specific type for each subclass to avoid downcasts.
ObjectFoo
public class ObjectFoo implements Foo {
private Object value;
public ObjectFoo(Object value) {
this.value = value;
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
#Override
public Object getValue() {
return value;
}
}
StringFoo
public class StringFoo implements Foo {
private String value;
public StringFoo(String string) {
this.value = string;
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
#Override
public String getValue() {
return value;
}
}
IntegerFoo
public class IntegerFoo implements Foo {
private Integer value;
public IntegerFoo(Integer integer) {
this.value = integer;
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
#Override
public Integer getValue() {
return value;
}
}
Here is the DisplayVisitor class visiting Foo subclasses :
public class DisplayVisitor {
void visit(ObjectFoo f) {
System.out.println("object=" + f.getValue());
}
void visit(IntegerFoo f) {
System.out.println("integer=" + f.getValue());
}
void visit(StringFoo f) {
System.out.println("string=" + f.getValue());
}
}
And here is a sample code to test the implementation :
public class OOP {
void test() {
List<Foo> foos = Arrays.asList(new StringFoo("a String"),
new StringFoo("another String"),
new IntegerFoo(1),
new ObjectFoo(new AtomicInteger(100)));
DisplayVisitor visitor = new DisplayVisitor();
for (Foo foo : foos) {
foo.accept(visitor);
}
}
public static void main(String[] args) {
OOP oop = new OOP();
oop.test();
}
}
Output :
string=a String
string=another String
integer=1
object=100
Improving the implementation
The actual implementation requires the introduction of a specific wrapper class for each buit-in type we want to wrap.
As discussed, we don't have the choice to operate a double dispatch.
But note that the repeated code in Foo subclasses could be avoided :
private Integer value; // or String or Object
#Override
public Object getValue() {
return value;
}
We could indeed introduce a abstract generic class that holds the user value and provides an accessor to :
public abstract class Foo<T> {
private T value;
public Foo(T value) {
this.value = value;
}
public abstract void accept(DisplayVisitor v);
public T getValue() {
return value;
}
}
Now Foo sublasses are lighter to declare :
public class IntegerFoo extends Foo<Integer> {
public IntegerFoo(Integer integer) {
super(integer);
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
}
public class StringFoo extends Foo<String> {
public StringFoo(String string) {
super(string);
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
}
public class ObjectFoo extends Foo<Object> {
public ObjectFoo(Object value) {
super(value);
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
}
And the test() method should be modified to declare a wildcard type (?) for the Foo type in the List<Foo> declaration.
void test() {
List<Foo<?>> foos = Arrays.asList(new StringFoo("a String object"),
new StringFoo("anoter String object"),
new IntegerFoo(1),
new ObjectFoo(new AtomicInteger(100)));
DisplayVisitor visitor = new DisplayVisitor();
for (Foo<?> foo : foos) {
foo.accept(visitor);
}
}
In fact, if really needed, we could simplify further Foo subclasses by introducing java code generation.
Declaring this subclass :
public class StringFoo extends Foo<String> {
public StringFoo(String string) {
super(string);
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
}
could as simple as declaring a class and adding an annotation on:
#Foo(String.class)
public class StringFoo { }
Where Foo is a custom annotation processed at compile time.
When calling a method that is overloaded, Java picks the most restrictive type based on the type of the variable passed to the function. It does not use the type of the actual instance.
this isn't polymoprhism, you've simply overloaded a method and called it with parameter of object type
Everything in Java is an Object/object (except primitive types). You store strings and integers as objects, and then as you call the prove method they are still referred to as objects. You should have a look at the instanceof keyword. Check this link
void prove(Object o){
if (o instanceof String)
System.out.println("String");
....
}

How can I pass a method to a constructor? [duplicate]

I am looking for a way to pass a method by reference. I understand that Java does not pass methods as parameters, however, I would like to get an alternative.
I've been told interfaces are the alternative to passing methods as parameters but I don't understand how an interface can act as a method by reference. If I understand correctly an interface is simply an abstract set of methods that are not defined. I don't want to send an interface that needs to be defined every time because several different methods could call the same method with the same parameters.
What I would like to accomplish is something similar to this:
public void setAllComponents(Component[] myComponentArray, Method myMethod) {
for (Component leaf : myComponentArray) {
if (leaf instanceof Container) { //recursive call if Container
Container node = (Container) leaf;
setAllComponents(node.getComponents(), myMethod);
} //end if node
myMethod(leaf);
} //end looping through components
}
invoked such as:
setAllComponents(this.getComponents(), changeColor());
setAllComponents(this.getComponents(), changeSize());
Edit: as of Java 8, lambda expressions are a nice solution as other answers have pointed out. The answer below was written for Java 7 and earlier...
Take a look at the command pattern.
// NOTE: code not tested, but I believe this is valid java...
public class CommandExample
{
public interface Command
{
public void execute(Object data);
}
public class PrintCommand implements Command
{
public void execute(Object data)
{
System.out.println(data.toString());
}
}
public static void callCommand(Command command, Object data)
{
command.execute(data);
}
public static void main(String... args)
{
callCommand(new PrintCommand(), "hello world");
}
}
Edit: as Pete Kirkham points out, there's another way of doing this using a Visitor. The visitor approach is a little more involved - your nodes all need to be visitor-aware with an acceptVisitor() method - but if you need to traverse a more complex object graph then it's worth examining.
In Java 8, you can now pass a method more easily using Lambda Expressions and Method References. First, some background: a functional interface is an interface that has one and only one abstract method, although it can contain any number of default methods (new in Java 8) and static methods. A lambda expression can quickly implement the abstract method, without all the unnecessary syntax needed if you don't use a lambda expression.
Without lambda expressions:
obj.aMethod(new AFunctionalInterface() {
#Override
public boolean anotherMethod(int i)
{
return i == 982
}
});
With lambda expressions:
obj.aMethod(i -> i == 982);
Here is an excerpt from the Java tutorial on Lambda Expressions:
Syntax of Lambda Expressions
A lambda expression consists of the following:
A comma-separated list of formal parameters enclosed in parentheses. The CheckPerson.test method contains one parameter, p,
which represents an instance of the Person class.Note: You
can omit the data type of the parameters in a lambda expression. In
addition, you can omit the parentheses if there is only one parameter.
For example, the following lambda expression is also valid:
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
The arrow token, ->
A body, which consists of a single expression or a statement block. This example uses the following expression:
p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
If you specify a single expression, then the Java runtime evaluates the expression and then returns its value. Alternatively,
you can use a return statement:
p -> {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). However, you do not have
to enclose a void method invocation in braces. For example, the
following is a valid lambda expression:
email -> System.out.println(email)
Note that a lambda expression looks a lot like a method declaration;
you can consider lambda expressions as anonymous methods—methods
without a name.
Here is how you can "pass a method" using a lambda expression:
interface I {
public void myMethod(Component component);
}
class A {
public void changeColor(Component component) {
// code here
}
public void changeSize(Component component) {
// code here
}
}
class B {
public void setAllComponents(Component[] myComponentArray, I myMethodsInterface) {
for(Component leaf : myComponentArray) {
if(leaf instanceof Container) { // recursive call if Container
Container node = (Container)leaf;
setAllComponents(node.getComponents(), myMethodInterface);
} // end if node
myMethodsInterface.myMethod(leaf);
} // end looping through components
}
}
class C {
A a = new A();
B b = new B();
public C() {
b.setAllComponents(this.getComponents(), component -> a.changeColor(component));
b.setAllComponents(this.getComponents(), component -> a.changeSize(component));
}
}
Class C can be shortened even a bit further by the use of method references like so:
class C {
A a = new A();
B b = new B();
public C() {
b.setAllComponents(this.getComponents(), a::changeColor);
b.setAllComponents(this.getComponents(), a::changeSize);
}
}
Since Java 8 there is a Function<T, R> interface (docs), which has method
R apply(T t);
You can use it to pass functions as parameters to other functions. T is the input type of the function, R is the return type.
In your example you need to pass a function that takes Component type as an input and returns nothing - Void. In this case Function<T, R> is not the best choice, since there is no autoboxing of Void type. The interface you are looking for is called Consumer<T> (docs) with method
void accept(T t);
It would look like this:
public void setAllComponents(Component[] myComponentArray, Consumer<Component> myMethod) {
for (Component leaf : myComponentArray) {
if (leaf instanceof Container) {
Container node = (Container) leaf;
setAllComponents(node.getComponents(), myMethod);
}
myMethod.accept(leaf);
}
}
And you would call it using method references:
setAllComponents(this.getComponents(), this::changeColor);
setAllComponents(this.getComponents(), this::changeSize);
Assuming that you have defined changeColor() and changeSize() methods in the same class.
If your method happens to accept more than one parameter, you can use BiFunction<T, U, R> - T and U being types of input parameters and R being return type. There is also BiConsumer<T, U> (two arguments, no return type). Unfortunately for 3 and more input parameters, you have to create an interface by yourself. For example:
public interface Function4<A, B, C, D, R> {
R apply(A a, B b, C c, D d);
}
Use the java.lang.reflect.Method object and call invoke
First define an Interface with the method you want to pass as a parameter
public interface Callable {
public void call(int param);
}
Implement a class with the method
class Test implements Callable {
public void call(int param) {
System.out.println( param );
}
}
// Invoke like that
Callable cmd = new Test();
This allows you to pass cmd as parameter and invoke the method call defined in the interface
public invoke( Callable callable ) {
callable.call( 5 );
}
While this is not yet valid for Java 7 and below, I believe that we should look to the future and at least recognize the changes to come in new versions such as Java 8.
Namely, this new version brings lambdas and method references to Java (along with new APIs, which are another valid solution to this problem. While they still require an interface no new objects are created, and extra classfiles need not pollute output directories due to different handling by the JVM.
Both flavors(lambda and method reference) require an interface available with a single method whose signature is used:
public interface NewVersionTest{
String returnAString(Object oIn, String str);
}
Names of methods will not matter from here on. Where a lambda is accepted, a method reference is as well. For example, to use our signature here:
public static void printOutput(NewVersionTest t, Object o, String s){
System.out.println(t.returnAString(o, s));
}
This is just a simple interface invocation, up until the lambda1 gets passed:
public static void main(String[] args){
printOutput( (Object oIn, String sIn) -> {
System.out.println("Lambda reached!");
return "lambda return";
}
);
}
This will output:
Lambda reached!
lambda return
Method references are similar. Given:
public class HelperClass{
public static String testOtherSig(Object o, String s){
return "real static method";
}
}
and main:
public static void main(String[] args){
printOutput(HelperClass::testOtherSig);
}
the output would be real static method. Method references can be static, instance, non-static with arbitrary instances, and even constructors. For the constructor something akin to ClassName::new would be used.
1 This is not considered a lambda by some, as it has side effects. It does illustrate, however, the use of one in a more straightforward-to-visualize fashion.
Last time I checked, Java is not capable of natively doing what you want; you have to use 'work-arounds' to get around such limitations. As far as I see it, interfaces ARE an alternative, but not a good alternative. Perhaps whoever told you that was meaning something like this:
public interface ComponentMethod {
public abstract void PerfromMethod(Container c);
}
public class ChangeColor implements ComponentMethod {
#Override
public void PerfromMethod(Container c) {
// do color change stuff
}
}
public class ChangeSize implements ComponentMethod {
#Override
public void PerfromMethod(Container c) {
// do color change stuff
}
}
public void setAllComponents(Component[] myComponentArray, ComponentMethod myMethod) {
for (Component leaf : myComponentArray) {
if (leaf instanceof Container) { //recursive call if Container
Container node = (Container) leaf;
setAllComponents(node.getComponents(), myMethod);
} //end if node
myMethod.PerfromMethod(leaf);
} //end looping through components
}
Which you'd then invoke with:
setAllComponents(this.getComponents(), new ChangeColor());
setAllComponents(this.getComponents(), new ChangeSize());
If you don't need these methods to return something, you could make them return Runnable objects.
private Runnable methodName (final int arg) {
return (new Runnable() {
public void run() {
// do stuff with arg
}
});
}
Then use it like:
private void otherMethodName (Runnable arg){
arg.run();
}
Java-8 onwards
Java 8 onwards, you can provide the implementation of the abstract method of a functional interface (an interface that has only one abstract method) using a lambda expression and pass the same to a method as a parameter.
#FunctionalInterface
interface ArithmeticFunction {
public int calcualate(int a, int b);
}
public class Main {
public static void main(String args[]) {
ArithmeticFunction addition = (a, b) -> a + b;
ArithmeticFunction subtraction = (a, b) -> a - b;
int a = 20, b = 5;
System.out.println(perform(addition, a, b));
// or
System.out.println(perform((x, y) -> x + y, a, b));
System.out.println(perform(subtraction, a, b));
// or
System.out.println(perform((x, y) -> x - y, a, b));
}
static int perform(ArithmeticFunction function, int a, int b) {
return function.calcualate(a, b);
}
}
Output:
25
25
15
15
ONLINE DEMO
Learn more about it from Method References.
I didn't find any example explicit enough for me on how to use java.util.function.Function for simple method as parameter function. Here is a simple example:
import java.util.function.Function;
public class Foo {
private Foo(String parameter) {
System.out.println("I'm a Foo " + parameter);
}
public static Foo method(final String parameter) {
return new Foo(parameter);
}
private static Function parametrisedMethod(Function<String, Foo> function) {
return function;
}
public static void main(String[] args) {
parametrisedMethod(Foo::method).apply("from a method");
}
}
Basically you have a Foo object with a default constructor. A method that will be called as a parameter from the parametrisedMethod which is of type Function<String, Foo>.
Function<String, Foo> means that the function takes a String as parameter and return a Foo.
The Foo::Method correspond to a lambda like x -> Foo.method(x);
parametrisedMethod(Foo::method) could be seen as x -> parametrisedMethod(Foo.method(x))
The .apply("from a method") is basically to do parametrisedMethod(Foo.method("from a method"))
Which will then return in the output:
>> I'm a Foo from a method
The example should be running as is, you can then try more complicated stuff from the above answers with different classes and interfaces.
Java do have a mechanism to pass name and call it. It is part of the reflection mechanism.
Your function should take additional parameter of class Method.
public void YouMethod(..... Method methodToCall, Object objWithAllMethodsToBeCalled)
{
...
Object retobj = methodToCall.invoke(objWithAllMethodsToBeCalled, arglist);
...
}
I did not found any solution here that show how to pass method with parameters bound to it as a parameter of a method. Bellow is example of how you can pass a method with parameter values already bound to it.
Step 1: Create two interfaces one with return type, another without. Java has similar interfaces but they are of little practical use because they do not support Exception throwing.
public interface Do {
void run() throws Exception;
}
public interface Return {
R run() throws Exception;
}
Example of how we use both interfaces to wrap method call in transaction. Note that we pass method with actual parameters.
//example - when passed method does not return any value
public void tx(final Do func) throws Exception {
connectionScope.beginTransaction();
try {
func.run();
connectionScope.commit();
} catch (Exception e) {
connectionScope.rollback();
throw e;
} finally {
connectionScope.close();
}
}
//Invoke code above by
tx(() -> api.delete(6));
Another example shows how to pass a method that actually returns something
public R tx(final Return func) throws Exception {
R r=null;
connectionScope.beginTransaction();
try {
r=func.run();
connectionScope.commit();
} catch (Exception e) {
connectionScope.rollback();
throw e;
} finally {
connectionScope.close();
}
return r;
}
//Invoke code above by
Object x= tx(() -> api.get(id));
Example of solution with reflection, passed method must be public
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
public class Program {
int i;
public static void main(String[] args) {
Program obj = new Program(); //some object
try {
Method method = obj.getClass().getMethod("target");
repeatMethod( 5, obj, method );
}
catch ( NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
System.out.println( e );
}
}
static void repeatMethod (int times, Object object, Method method)
throws IllegalAccessException, InvocationTargetException {
for (int i=0; i<times; i++)
method.invoke(object);
}
public void target() { //public is necessary
System.out.println("target(): "+ ++i);
}
}
Use the Observer pattern (sometimes also called Listener pattern):
interface ComponentDelegate {
void doSomething(Component component);
}
public void setAllComponents(Component[] myComponentArray, ComponentDelegate delegate) {
// ...
delegate.doSomething(leaf);
}
setAllComponents(this.getComponents(), new ComponentDelegate() {
void doSomething(Component component) {
changeColor(component); // or do directly what you want
}
});
new ComponentDelegate()... declares an anonymous type implementing the interface.
Here is a basic example:
public class TestMethodPassing
{
private static void println()
{
System.out.println("Do println");
}
private static void print()
{
System.out.print("Do print");
}
private static void performTask(BasicFunctionalInterface functionalInterface)
{
functionalInterface.performTask();
}
#FunctionalInterface
interface BasicFunctionalInterface
{
void performTask();
}
public static void main(String[] arguments)
{
performTask(TestMethodPassing::println);
performTask(TestMethodPassing::print);
}
}
Output:
Do println
Do print
I'm not a java expert but I solve your problem like this:
#FunctionalInterface
public interface AutoCompleteCallable<T> {
String call(T model) throws Exception;
}
I define the parameter in my special Interface
public <T> void initialize(List<T> entries, AutoCompleteCallable getSearchText) {.......
//call here
String value = getSearchText.call(item);
...
}
Finally, I implement getSearchText method while calling initialize method.
initialize(getMessageContactModelList(), new AutoCompleteCallable() {
#Override
public String call(Object model) throws Exception {
return "custom string" + ((xxxModel)model.getTitle());
}
})
I appreciate the answers above but I was able to achieve the same behavior using the method below; an idea borrowed from Javascript callbacks. I'm open to correction though so far so good (in production).
The idea is to use the return type of the function in the signature, meaning that the yield has to be static.
Below is a function that runs a process with a timeout.
public static void timeoutFunction(String fnReturnVal) {
Object p = null; // whatever object you need here
String threadSleeptime = null;
Config config;
try {
config = ConfigReader.getConfigProperties();
threadSleeptime = config.getThreadSleepTime();
} catch (Exception e) {
log.error(e);
log.error("");
log.error("Defaulting thread sleep time to 105000 miliseconds.");
log.error("");
threadSleeptime = "100000";
}
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() {
// Do job here using --- fnReturnVal --- and return appropriate value
return null;
}
};
Future<Object> future = executor.submit(task);
try {
p = future.get(Integer.parseInt(threadSleeptime), TimeUnit.MILLISECONDS);
} catch (Exception e) {
log.error(e + ". The function timed out after [" + threadSleeptime
+ "] miliseconds before a response was received.");
} finally {
// if task has started then don't stop it
future.cancel(false);
}
}
private static String returnString() {
return "hello";
}
public static void main(String[] args) {
timeoutFunction(returnString());
}

How to reuse methods?

I am a beginner and i try to teach myself clean coding. I want to pass a function as a parameter that I can reuse a method without to repeat code. As an example I have this:
public class Dog {
private String name;
private int id;
private List<String> characteristic;
public List<String> getCharacteristic() {
return characteristic;
}
public void setCharacteristic(List<String> characteristic) {
this.characteristic = characteristic;
}
}
public class Check{
private List<Dog> dogs = new ArrayList();
public void iterate() {
while (dogs.size() > 0) {
for (Dog dog : dogs) {
List<String> restChara = new ArrayList<>();
restChara= checkChara(dog, restChara);
if (restChara.size()>0) {
dog.setCharacteristic(restChara);
} else {
dogs.remove(dog);
}
}
}
}
private List<String> checkChara(Dog dog, List<String> restChara) {
for (String chara : dog.getCharacteristic()) {
boolean charaChecked = doSomething(chara);
if (!charaChecked) {
restChara.add(chara);
} else {
dog.getCharacteristic().remove(chara);
}
}
return restChara;
}
private boolean doSomething(String chara){
//do sth.
return true;
}
private boolean doSomething2(String chara){
//do sth.
return true;
}
}
How would you define the method checkChara in order to use different functions within it?
My first thought was to pass the function as a parameter (i think it would be in C# delegates)
Thank you very much!
EDIT:
I think I found another pattern strategy design pattern
https://www.freecodecamp.org/news/the-strategy-pattern-explained-using-java-bc30542204e0/
Java does not support “directly” nested methods. Many functional programming languages support method within method. But you can achieve nested method functionality in Java 7 or older version by define local classes, class within method so this does compile. And in java 8 and newer version you achieve it by lambda expression.
Method 1 (Using anonymous subclasses)
It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overloading methods of a class or interface, without having to actually subclass a class.
//Java program implements method inside method
public class GFG {
// create a local interface with one abstract
// method run()
interface myInterface {
void run();
}
// function have implements another function run()
static void Foo()
{
// implement run method inside Foo() function
myInterface r = new myInterface() {
public void run()
{
System.out.println("geeksforgeeks");
};
};
r.run();
}
public static void main(String[] args)
{
Foo();
}
}
Method 2 (Using local classes)
You can also implement a method inside a local class. A class created inside a method is called local inner class. If you want to invoke the methods of local inner class, you must instantiate this class inside method.
// Java program implements method inside method
public class GFG {
// function have implementation of another
// function inside local class
static void Foo()
{
// local class
class Local {
void fun()
{
System.out.println("geeksforgeeks");
}
}
new Local().fun();
}
public static void main(String[] args)
{
Foo();
}
}
Method 3 (Using a lambda expression)
Lambda expressions basically express instances of functional interfaces (An interface with single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces.
// Java program implements method inside method
public class GFG {
interface myInterface {
void run();
}
// function have implements another function
// run() using Lambda expression
static void Foo()
{
// Lambda expression
myInterface r = () ->
{
System.out.println("geeksforgeeks");
};
r.run();
}
public static void main(String[] args)
{
Foo();
}
}
I don't exaclty know what you mean, but i figure out it could be something like that:
List<Runnable> runMyStuff = new ArrayList<Runnable>();
String variable= "Hallo"; //needs to be effectively final
runMyStuff.add(() -> {
System.out.println(variable);
doSomething(variable);
});
runMyStuff.add(() ->{
System.out.println("This is a test");
});
runMyStuff.add(() ->{
System.out.println("2 + 2 = " + (2+2) );
});
runMyStuff.get(0).run();
runMyStuff.get(2).run();
runMyStuff.get(0).run();
runMyStuff.get(1).run();
runMyStuff.get(2).run();
will result in :
Hallo
2 + 2 = 4
Hallo
This is a test
2 + 2 = 4
When you put variables or Passing Parameters in those runnable methods, they need to be effectively final or you pass them in a container.
You can re-run each method.
And within those Methods you can execute other methods.
NOTE:
If you want to have return Parameters you could do the same with Callable and than ".call()" instead of run.
EDIT:
Under the assumption you mean character Check or something like that
Example for charaCheck passable Method With Interface:
public interface CharacterChecker{
//is a template returns boolean, need a String param
public boolean call(String chara);
}
A method that executes a passes method of the type of "CHaracterChecker"
public static void excecutePassedMethod(CharacterChecker checker, String chara) {
System.out.println(chara + ": " + checker.call(chara));
}
Two different implementations of a "Character Checker"
CharacterChecker goodChecker = new CharacterChecker() {
#Override
public boolean call(String chara) {
return "good".equals(chara);
}
};
CharacterChecker lazyCheker = new CharacterChecker() {
#Override
public boolean call(String chara) {
return "lazy".equals(chara);
}
};
The Methods that are Passed the "method" (More like anonymos class object with the method)
excecutePassedMethod(goodChecker, "bad");
excecutePassedMethod(goodChecker, "good");
excecutePassedMethod(goodChecker, "jolly");
excecutePassedMethod(lazyCheker, "frisky");
excecutePassedMethod(lazyCheker, "lazy");
result will be:
bad: false
good: true
jolly: false
frisky: false
lazy: true

IIFE/Automatic Method in Java?

I know that there is a way to have a method to run automatically in java?. This is known as an IIFE in javascript, but is this possible in java?
Javascript IIFE:
(function() {
console.log('Hello!');
})();
Thank You! (I'm also just curious)
Here's an IIFE in Java:
((Function<String, String>) s -> {
String z = "'" + s + "'";
return z;
}).apply("aaa");
All of the following print "Hello world!"
JavaScript:
console.log((function() {
const x = "Hello world!";
return x;
})());
Java:
System.out.println(((Supplier<String>) () -> {
String x = "Hello world!";
return x;
}).get());
In Java it may feel more ergonomic to create a helper function to infer the type and execute the function for you:
public static <T> T iife(Supplier<? extends T> supplier) {
return supplier.get();
}
...
System.out.println(iife(() -> {
String x = "Hello world!";
return x;
}));
In general you might want to consider factoring out the function. But if the function is relatively small, and especially if it captures several variables, an IIFE may be more readable. I liken an IIFE to a block expression (which Java does not have).
Stumbled upon this question when looking for this idea myself. I think the closest thing Java has to JavaScript IIFEs would be an instance of an abstract class, whose only method, an execute method, is overriden during the instance creation and then executed immediately after the object's instantiation. You can even get the closure aspect of it too. However, you won't be able to change what the variable refers to inside the overriden method.
JavaScript:
let subject = 'World';
(() => {
console.log(`Hello, ${subject}!`);
})();
Java:
public abstract class Iife {
public abstract void execute();
}
public class Main {
public static void main(String[] args) {
String subject = "World";
new Iife() {
#Override
public void execute() {
System.out.println("Hello, " + subject + "!");
}
}.execute();
}
}
There is no direct way as mentioned by other people above.
Anonymous Inner Class with init() Initializer
I feel that this could be used like IIFEs but the problem is that it needs to be inside another class
Thread T = new Thread() {
private int num;
Thread init(int num){
this.num = num;
return this;
}
#Override
public void run() {
// computes and outputs the factorial of num
int res = 1;
for (int i = 1; i <= num; i++) {
res *= i;
}
System.out.println(res);
}
}.init(3);
The init() can be used to pass parameters to be used for working
In a static context, you can define code wrapped within brackets using the static modifier:
public class MyClass{
static{
System.out.println("Running static");
}
}
In the context of Objects, you can wrap the code in the same manner without the static modifier:
public class MyClass{
{
System.out.println("Initializing");
}
}
Java will automatically run the "public static void main(String[] args)" method in the class specified.
There is no IIFE in java.
Java is statically typed & compiled as opposed to javascript which is dynamically typed and interpreted.
In java there is only one entry point to a program which is the method main which is static and public.
In Groovy (JVM base language) you can use repl where defined method (functions are method in java terminology) can be invoked later which may be the nearest thing to IIFE.

Full Fledged Multiple Inheritance in Java 8

It seems that Java 8 allows full fledged inheritance with a simple framework as below, using Static and Default methods on interfaces.
While its always possible to misuse and write stupid code, these new features make it quite easy to achieve multiple inheritance, even if the designers of the language meant to stay away from it.
Is this a simple implementation of Multiple Inheritance using Interfaces as base classes, or a misuse of the language?
Did Java designers go too far in allowing this?
package PseudoMultipleInheritance;
import java.util.HashMap;
abstract class InstanceMap<T,T2>
{
HashMap<Object,Object> instances = new HashMap<Object, Object>();
abstract T2 createMembersInstance();
T2 getMembersInstance(T thisObject )
{
if ( !instances.containsKey(thisObject) )
instances.put(thisObject,createMembersInstance());
return (T2) instances.get(thisObject);
}
}
interface A
{
class Members
{
int x; // just an example of an inheritable member
}
InstanceMap<A,A.Members> instanceMap = new InstanceMap<A, A.Members>() { A.Members createMembersInstance() {return new A.Members(); }};
default A.Members thisA() { return instanceMap.getMembersInstance(this); }
default int getX()
{
return thisA().x; // // just an example of an inheritable getter
}
default void setX(int x)
{
thisA().x = x; // just an example of an inheritable setter
}
}
interface B
{
class Members
{
int y; // just an example of an inheritable member
}
InstanceMap<B,B.Members> instanceMap = new InstanceMap<B, B.Members>() { B.Members createMembersInstance() {return new B.Members();} };
default B.Members thisB() { return instanceMap.getMembersInstance(this); }
default int getYLastDigit()
{
return thisB().y % 10; // just an example of an inheritable function
}
default void incrementY(int x)
{
thisB().y += x; // just an example of an inheritable function
}
}
class C implements A, B
{
}
public class Example04AlmostMultipleInheritance {
public static void main(String[] args) {
C c1 = new C();
C c2 = new C();
c1.setX(5);
c2.setX(3);
System.out.println(c1.getX()); // prints 5
System.out.println(c2.getX()); // prints 3
c1.incrementY(99);
System.out.println(c1.getYLastDigit()); // prints 9
}
}
///////////////////////////////////////////////////
Or for yet another option:
interface A
{
class Members
{
public int x; // just an example of an inheritable member
void showX() { System.out.println(x); } // just an example of an inheritable function
}
InstanceMap<A,A.Members> instanceMap = new InstanceMap<A, A.Members>() { A.Members createMembersInstance() {return new A.Members(); }};
default A.Members getA() { return instanceMap.getMembersInstance(this); }
}
interface B
{
class Members
{
int y; // just an example of an inheritable member
}
InstanceMap<B,B.Members> instanceMap = new InstanceMap<B, B.Members>() { B.Members createMembersInstance() {return new B.Members();} };
default B.Members getB() { return instanceMap.getMembersInstance(this); }
}
class C implements A, B
{
}
public class Example04AlmostMultipleInheritance {
public static void main(String[] args) {
C c1 = new C();
C c2 = new C();
c1.getA().x = 5;
c2.getA().x = 3;
c1.getA().showX(); // prints 5
c2.getA().showX(); // prints 3
c1.getB().y = 99;
System.out.println(c1.getB().y % 10); // prints 9
}
}
Implementing an interface is not inheritance. It's as simple as that.
what if someone implements both your interfaces but supplies a different implementation than the default one?
So no, this is not multiple inheritance, It's simply a way to write your code that depends on nobody actually implementing their own version of the default methods. Which means that it depends on people not actually using interfaces the way they're supposed to, because they are supposed to be able to implement their own methods instead of the defaults, but if they actually do that your "multiple inheritance" does not work as expected.
So I'd actually consider this to be misuse of the language.
It is A form of multiple inheritance, but it's not the "Diamond Problem" that is usually brought up when discussing multiple inheritence. Java's implementation is almost the same as Scala's solution to the same thing, which is somewhat similar to how Python implements multiple inheritance.
no, see example of multiple inheritance here: http://java.dzone.com/articles/interface-default-methods-java

Categories