Calling the static methods of a java/groovy object using reflection - java

I'm working on a groovy unit-testing class that contains a collection of rules for whether or not the contents of a file are correctly formatted. (Not using a proper rules engine, it just takes advantage of Groovy's assertion capabilities to do validation in a way that vaguely resembles what a rules engine would do.) I was thinking that I could create a method called FireAllRules that looks like this:
public static void FireAllRules(File file)
{
for(def method in Class.getMethods)
{
if(method.name.indexOf("rule" == 0) method.invoke(file);
}
}
All the methods that I want the loop to pick up on are static, and I noticed during the debugging process none of my rule methods are included in the Class.getMethods() enumeration. Ideally, I would like to only loop over the methods that I personally wrote into the class rather than sorting through dozens of uninteresting methods that come in along with java.Object. Is there a way to use reflection to iterate over these static methods at runtime?

Given:
class Test {
public static testThis() {
println "Called testThis"
}
public static woo() {
println "Called woo"
}
public static testOther() {
println "Called testOther"
}
}
You can do:
Test.metaClass.methods.grep { it.static && it.name.startsWith( 'test' ) }.each {
it.invoke( Test )
}
To print:
Called testOther
Called testThis
A more generic method to execute the static test methods of a class would be:
def invokeClass( clazz ) {
clazz.metaClass.methods.grep { it.static && it.name.startsWith( 'test' ) }.each {
it.invoke( clazz )
}
}
invokeClass( Test )

Static methods are included in the methods returned by getMethods(). Your issue might be method.name.indexOf("rule" == 0). This should be method.name.indexOf("rule") == 0, or better yet method.name.startsWith("rule").
Also, are your rule methods public? If not, you can use getDeclaredMethods(). To invoke them, you will have to call setAccessible() first.

The java version would be something like this (I've removed the imports and exceptions for clarity).
public class FindAndRunStaticMethods {
public static void main(String[] args) {
fireAllRules();
}
public static void fireAllRules() {
for(Method method : StaticMethodClass.class.getDeclaredMethods()) {
findAndRunRules(method);
}
}
private static void findAndRunRules(Method method) {
if (!Modifier.isStatic(method.getModifiers())) return;
if (!method.getName().startsWith("rule")) return;
if (!method.getReturnType().equals(Void.TYPE)) return;
Class[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length != 1) return;
if (!parameterTypes[0].equals(File.class)) return;
method.invoke(null, new File("dummy"));
}
}
A sample test class could look like this
public class StaticMethodClass {
public static void ruleHere(File x) { System.out.println("should print"); }
public static void ruleRun(File x) { System.out.println("should print"); }
public void ruleNotSelected() { System.out.println("not run"); }
}

Related

Is there any straightforward way to fetch and send `current method name` as argument in java?

Making an api to log and provide common methods.
public static void start(Class<?> clazz) throws IOException {
writeExecutionLog("Start of" + clazz.getName(), null);
}
public static void end(Class<?> clazz) throws IOException {
writeExecutionLog("End of" + clazz.getName(), null);
}
In classes, There are multiple schedulers in different methods which calls above start and end when job is started or finsihed.
class scheduler{
public void scheduler1(){
MyService.start(methodname or class)
MyService.end(methodname or class)
}
public void scheduler2(){
MyService.start(methodname or class)
MyService.end(methodname or class)
}
}
In place of String, is there any simple way to pass Method name with class name in above start and end method.
I want to fetch current method name dynamically in Start and end methods something like this.class.currentMethod?(not complicated statement like mentioned in geekofgeeks and better if i can handle most of things in start() and end())
You could generate a stack trace and parse the line. It's versatile but expensive.
public static void start() throws IOException {
writeExecutionLog("Start of" + new Throwable().getStackTrace()[1].getMethodName(), null);
}
String methodName = new Object() {}
.getClass()
.getEnclosingMethod()
.getName();
in your method should work.
You are reinventing the wheel, as logging APIs do already exist and are capable of identifying the method.
Taking the built-in logging API java.util.logging.*, a very simple example demonstrating the capability would be
public class MethodNameExample1 {
static final Logger MY_SERVICE = Logger.getAnonymousLogger();
static {
MY_SERVICE.setUseParentHandlers(false);
MY_SERVICE.addHandler(new Handler() {
public void publish(LogRecord lr) {
System.out.println(lr.getSourceClassName()+"."+lr.getSourceMethodName()
+" "+lr.getMessage()+"ed");
}
public void flush() {}
public void close() {}
});
}
public static void main(String[] args) {
MY_SERVICE.info("enter");
firstExample();
Inner.thirdExample();
MY_SERVICE.info("exit");
}
static void firstExample() {
MY_SERVICE.info("enter");
secondExample();
MY_SERVICE.info("exit");
}
static void secondExample() {
MY_SERVICE.info("enter");
MY_SERVICE.info("exit");
}
static class Inner {
static void thirdExample() {
MY_SERVICE.info("enter");
//...
MY_SERVICE.info("exit");
}
}
}
MethodNameExample1.main entered
MethodNameExample1.firstExample entered
MethodNameExample1.secondExample entered
MethodNameExample1.secondExample exited
MethodNameExample1.firstExample exited
MethodNameExample1$Inner.thirdExample entered
MethodNameExample1$Inner.thirdExample exited
MethodNameExample1.main exited
When you want to have more control over this (or insist on creating your own logging API implementation), Java 9’s StackWalker is the way to go. Unlike capturing a stack trace like with new Throwable().getStackTrace(), the stack walker supports extracting only the needed information, including hinting about the maximum number of frames we intend to traverse, so the JVM doesn’t need to process more than necessary and may apply further optimizations:
public class MethodNameExample2 {
public static class MyService {
private static final StackWalker STACK_WALKER=StackWalker.getInstance(Set.of(), 3);
public static void enter() {
System.out.println(getCaller()+" entered");
}
public static void exit() {
System.out.println(getCaller()+" exited");
}
private static String getCaller() {
return STACK_WALKER.walk(frames -> frames.skip(2)
.map(f -> f.getClassName()+'.'+f.getMethodName())
.findFirst().orElse("unknown caller"));
}
}
public static void main(String[] args) {
MyService.enter();
firstExample();
Inner.thirdExample();
MyService.exit();
}
static void firstExample() {
MyService.enter();
secondExample();
MyService.exit();
}
static void secondExample() {
MyService.enter();
MyService.exit();
}
static class Inner {
static void thirdExample() {
MyService.enter(); MyService.exit();
}
}
}
MethodNameExample2.main entered
MethodNameExample2.firstExample entered
MethodNameExample2.secondExample entered
MethodNameExample2.secondExample exited
MethodNameExample2.firstExample exited
MethodNameExample2$Inner.thirdExample entered
MethodNameExample2$Inner.thirdExample exited
MethodNameExample2.main exited
Your task should be done using AOP (Aspect oriented programming)
[AOP] aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding additional behavior to existing code (an advice) without modifying the code itself, instead separately specifying which code is modified via a "pointcut" specification, such as "log all function calls when the function's name begins with 'set'".
For example, you can mark all your scheduler methods with a custom annotation (or use method name, package name etc.) and the create an aspect
#Around("#annotation(LogExecutionTime)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
logger.debug("start of ...")
Object proceed = joinPoint.proceed();
logger.debug("end of ...")
return proceed;
}
from ProceedingJoinPoint you can extract a lot of information not just method name.

JUnit - test that a method has been called

I'm new to unit testing, and I'm trying to test that a method has been called. The method in question doesn't return anything.
public void example (boolean foo) {
if (foo) {
processFoo(foo);
}
else if (foo==false) {
processSomethingElse(foo);
}
}
I want to be able to test that the processFoo method is being called, but I don't know how to do that.
If mocking is required, then I have to use JMockit. Thanks!
Sorry I'm a little late to the party, but I have a couple of ideas for you.
First, you mention that one option is to use JMockit--that's great as it gives you a lot of flexibility. If you use JMockit, then the visibility of your processFoo() method doesn't much matter. Let's see what that might look like:
public class Subject {
public void example (boolean foo) {
if (foo) {
processFoo(foo);
}
else if (foo==false) {
processSomethingElse(foo);
}
}
private void processFoo(boolean b) {
System.out.println("b = " + b);
}
private void processSomethingElse(boolean bb) {
System.out.println("bb = " + bb);
}
}
So, one caveat with this option, though is that I'm going to assume processFoo() is a method on your test subject and I'm going to use a partial mock to change the test subject--not something I really like to do, but this is an example. In general, it is best to only mock the dependencies of your test subject rather than behavior of the test subject itself--you have been advised! Note that the processFoo() method of the test subject is private. I'm going to substitute a method for the test with JMockit's partial mocking and the visibility of that new method does not have to match the original.
import static org.assertj.core.api.Assertions.assertThat;
import mockit.Mock;
import mockit.MockUp;
import mockit.integration.junit4.JMockit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
#RunWith(JMockit.class)
public class SubjectTest {
private Subject testSubject = new Subject();
private boolean processFooCalled = false;
#Before
public void setup() {
new MockUp<Subject>() {
#Mock
public void processFoo(boolean b) {
processFooCalled = true;
};
};
}
#Test
public void should_call_processFoo() {
testSubject.example(true);
assertThat(processFooCalled).isTrue();
}
#Test
public void should_not_call_processFoo() {
testSubject.example(false);
assertThat(processFooCalled).isFalse();
}
}
Ok, so that was the first option. It's actually a little easier if you forget JMockit for this one, assuming you are able to subclass your test subject and override the processFoo() method:
public class Subject {
public void example (boolean foo) {
if (foo) {
processFoo(foo);
}
else if (foo==false) {
processSomethingElse(foo);
}
}
protected void processFoo(boolean b) { // NOTE: protected access here!
System.out.println("b = " + b);
}
private void processSomethingElse(boolean bb) {
System.out.println("bb = " + bb);
}
}
So, in this case, the strategy is simply to subclass your test subject and replace the implementation of the method you wish to observe being called. It might look like this:
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class SubjectTest2 {
private Subject testSubject = new TestableSubject();
private boolean processFooCalled = false;
#Test
public void should_call_processFoo() {
testSubject.example(true);
assertThat(processFooCalled).isTrue();
}
#Test
public void should_not_call_processFoo() {
testSubject.example(false);
assertThat(processFooCalled).isFalse();
}
class TestableSubject extends Subject {
#Override
protected void processFoo(boolean b) {
processFooCalled = true;
}
}
}
Give it a whirl. Hope it helps!
You could use a counter variable in your class and increment it whenever the method is called, or use a print statement. If you don't have access to the processFoo method, a simple approach would be to do this at the time that processFoo is called in another method, if that's the only place where it can possibly be called.
For example:
public static int processFooCalls = 0;
// ...
public void example (boolean foo) {
if (foo) {
processFoo(foo);
processFooCalls += 1;
// and/or
System.out.println("processFoo method was called");
}
// ...
}
public static void main (String[] args) {
// main routine here...
System.out.println("'processFoo' was called " + processFooCalls + " times.");
}
If processFoo can be called elsewhere, and you need to consider this possibility as well, then you'll need to have access to the processFoo code in order to do this, e.g.:
void processFoo( boolean b ) {
// increment number of times processFoo was called here, and/or print, as follows
processFooCalls += 1;
System.out.println("called processFoo method!");
/* some functionality */
}
Looking at the JMockit documentation, you will need the following tools:
Static Mocking: http://jmockit.github.io/tutorial/BehaviorBasedTesting.html#staticPartial
Invocation Counts: http://jmockit.github.io/tutorial/BehaviorBasedTesting.html#constraints
Combining the two in a test (my syntax may be a little off since I'm more accustomed to Mockito, but the concept should hold):
#Test
public void someTestMethod(#Mocked({"processFoo"}) final ExampleClass exampleclass)
{
new Expectations() {{
exampleclass.processFoo(); times = 1;
}};
exampleclass.example(true);
}
This should mock the processFoo method, leaving everything else intact, and checks to make sure it is called exactly once.
Don't consider doing any kind of partial mocking for this, all you're doing in that case is ensuring that if you want to refactor your code your tests will fail. There is a mantra in unit testing - "never test private methods".
What you should be doing is testing that the method you call conforms to the behaviour you want to see. In this case what happens when foo is true is what's important, not that it calls processFoo. So if foo is true you want to be testing that the action processFoo carries out is true and nothing else.

Can I use an If statement to check which method made the call?

I want to make an if statement that checks to see which method made the call to a secondary method.
I will write what i want in pseudo code so you can see what I mean.
public static void methodOne() {
methodToCall();
}
public static void methodTwo() {
methodToCall();
}
public static void methodThree() {
methodToCall();
}
public static void methodToCall() {
if (methodOne made the call == true) {
execute this
} else if (methodTwo made the call == true){
execute this
} else if (methodThree made the call == true){
execute this
} else {
System.out.println("How did you get here?");
}
}
That's about the gist of it. I want a simple check to see which method made the call so I can choose which operation is relevant to the call.
Is this possible?
If it is not possible, is there a work around?
This is called 'state orientation', and it was debated extensively in the 1970s, possibly even the 1960s. The conclusion was that if you need to know this sort of thing you are already doing something seriously wrong, by introducing a two-way dependency into the code. What happens for example when you add another caller?
Use three short methods, instead of combining the logic of three short methods into one larger method. Once the short methods are created Just call the appropriate method from each calling method.
public static void methodOne() {
methodToCall1();
}
public static void methodTwo() {
methodToCall2();
}
public static void methodThree() {
methodToCall3();
}
public static void methodToCall1() {
int x = 0;
x = x - 3; //some custom logic to prep argument
commonLogic(x);
}
public static void methodToCall2() {
//Method 2 logic
int x = 0;
x = x + 3; //some custom logic to prep argument
commonLogic(x);
}
public static void methodToCall3() {
//Method 3 logic
int x = 0;
x = x * 3; //some custom logic to prep argument
commonLogic(x);
}
public static void commonLogic(int arg1){
//peform common logic
}
If these three methods would contain duplicate code, abstract the duplicate code into another method then call that method from within each of the smaller methods. The idea is to prepare the arguments to call the common function in each of the three smaller functions, then call the common function with those arguments.
A great deal of the abstraction afforded by methods comes from the fact that they do not need to know who is calling them, so the answer to your question is "no". It does not mean that you cannot make it work, though: make the callers pass some sort of a token (say, an enum value) identifying themselves to the callee. This would let you dispatch on that identity inside your method's implementation:
enum CallerContext {CALLER1, CALLER2, CALLER3};
...
public static void methodToCall(CallerContext context) {
...
}
This is not the most Object-Oriented way of doing things, however: very often, a better approach would be letting the callers supply the logic to be executed, rather than supplying a token identifies that logic. See Visitor Pattern for details on that approach.
You can do it by examining the call stack via Thread.getStackTrace():
public static void methodToCall(Action action) {
String callingMethod = Thread.currentThread().getStackTrace()[2].getMethodName();
if (callingMethod.equals("methodOne")) {
execute this0
} else if (callingMethod.equals("methodTwo")) {
execute this
} else if (callingMethod.equals("methodThree")) {
execute this
} else {
System.out.println("How did you get here?");
}
}
but you shouldn't - it's a bit anti-OO. Instead, change your method signature to something like this:
public enum Action {ONE, TWO, THREE}
public static void methodToCall(Action action) {
if (action == ONE) {
execute this
} else if (action == TWO) {
execute this
} else if (action == THREE) {
execute this
} else {
System.out.println("How did you get here?");
}
}
If you end up using an enum, then make sure to take advantage of the fact that enums in Java are no less than singleton instances of classes. Therefore you can declare the method as abstract in the enum definition and then override it in each instance, instead of passing the enum as a paramater to some method defined outside of the enum's context.
So it would look something like:
enum Method {
Mode1 {
#Override
void call() {
// do stuff
}
}, Mode2 {
#Override
void call() {
// do stuff differently
}
}, Mode3 {
#Override
void call() {
// do stuff even more differently
}
};
abstract void call();
}
And then you either don't need your wrapping methods, or, if they were supposed to do anything more, you write:
public static void methodOne() {
// some code
Method.Mode1.call();
// some code
}

Detecting whether a method/function exists in Java

Is there a method/function in Java that checks if another method/function is available just like function_exists(functionName) in PHP?
Here I am referring to a method/function of static class.
You can find out if a method exists in Java using reflection.
Get the Class object of the class you're interested in and call getMethod() with the method name and parameter types on it.
If the method doesn't exist, it will throw a NoSuchMethodException.
Also, please note that "functions" are called methods in Java.
Last but not least: keep in mind that if you think you need this, then chances are that you've got a design problem at hand. Reflection (which is what the methods to inspect the actual Java classes is called) is a rather specialized feature of Java and should not generally be used in business code (although it's used quite heavily and to some nice effects in some common libraries).
I suspect you're looking for Class.getDeclaredMethods and Class.getMethods which will give you the methods of a class. You can then test whether the one you're looking for exists or not, and what it's parameters are etc.
You can use Reflections to lookup if the method exists:
public class Test {
public static void main(String[] args) throws NoSuchMethodException {
Class clazz = Test.class;
for (Method method : clazz.getDeclaredMethods()) {
if (method.getName().equals("fooBar")) {
System.out.println("Method fooBar exists.");
}
}
if (clazz.getDeclaredMethod("fooBar", null) != null) {
System.out.println("Method fooBar exists.");
}
}
private static void fooBar() {
}
}
But Reflection is not really fast so be careful when to use it (probably cache it).
Try using the Class.getMethod() method of the Class class =)
public class Foo {
public static String foo(Integer x) {
// ...
}
public static void main(String args[]) throws Exception {
Method fooMethod = Foo.class.getMethod("foo", Integer.class);
System.out.println(fooMethod);
}
}
Here my solution using reflection...
public static boolean methodExists(Class clazz, String methodName) {
boolean result = false;
for (Method method : clazz.getDeclaredMethods()) {
if (method.getName().equals(methodName)) {
result = true;
break;
}
}
return result;
}
You can use the reflection API to achieve this.
YourStaticClass.getClass().getMethods();
You can do this like this
Obj.getClass().getDeclaredMethod(MethodName, parameterTypes)

Java Pass Method as Parameter

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());
}

Categories

Resources