I'm creating an API in Java for some of my projects, and I have one main problem. I need to allow for a call-back in it. The API is a web server API, which handles cookies, FS, Sockets, and even my own language ( I couldn't get PHP to work ), so now all I need to do, is when the server is asked to resolve content, the user should be asked what they want to do. I know some APIs can do this, where you define functions ( or whatever they're called ), and implement/extend the API class, and then the API can call those classes, but I can't figure out how to do that.
Jan Vladimir Mostert
Idea Incubator
I'm not sure if you're wanting to pass in a class or a function, but here goes both:
In Kotlin you would do something like this (I'm just adding it here for reference, I'm translating backwards from Kotlin to Java since my Java is a bit rusty):
fun foo(m: String, bar: (m: String) -> Unit) { bar(m) } fun buz1(m: String) { println("message1: $m") } fun buz2(m: String) { println("message2: $m") } fun something() { foo("hi", this::buz1) foo("hi", this::buz2) }In Java8+ you would use Lambdas:
public void foo(String m, Function<String, Void> bar) { bar.apply(m); } // this should be defined somewhere in a class Function<String, Void> buz1 = (String m) -> { System.out.println("message1: " + m); return null; }; // this should be defined somewhere in a class Function<String, Void> buz2 = (String m) -> { System.out.println("message2: " + m); return null; }; void something() { foo("test", buz1); foo("test", buz2); }For passing a class in instead of a function, you'd do something like this in Java
foo("Hello", String.class); public void foo(String m, Class clazz) { System.out.println("Hello " + clazz.getName()); }From that
clazzvariable, you can now get all the methods, getters and setters, constructors, etc and then call it dynamically. Do a search for Java Reflection to learn more about how to dynamically call methods in Java given only a method name.Hope it answers your question.