funções de retorno de chamada em Java
-
22-07-2019 - |
Pergunta
Existe uma maneira de passar uma função de chamada de volta em um método Java?
O comportamento que eu estou tentando imitar é um .Net Delegado sendo passado para uma função.
Eu vi pessoas sugerindo a criação de um objeto separado, mas que parece um exagero, mas estou ciente de que, por vezes, um exagero é a única maneira de fazer as coisas.
Solução
Se você somthing média como .NET anônima delegado, acho classe anônima de Java pode ser usado também.
public class Main {
public interface Visitor{
int doJob(int a, int b);
}
public static void main(String[] args) {
Visitor adder = new Visitor(){
public int doJob(int a, int b) {
return a + b;
}
};
Visitor multiplier = new Visitor(){
public int doJob(int a, int b) {
return a*b;
}
};
System.out.println(adder.doJob(10, 20));
System.out.println(multiplier.doJob(10, 20));
}
}
Outras dicas
Desde Java 8, há lambda e método referências:
Por exemplo, vamos definir:
public class FirstClass {
String prefix;
public FirstClass(String prefix){
this.prefix = prefix;
}
public String addPrefix(String suffix){
return prefix +":"+suffix;
}
}
e
import java.util.function.Function;
public class SecondClass {
public String applyFunction(String name, Function<String,String> function){
return function.apply(name);
}
}
Em seguida, você pode fazer:
FirstClass first = new FirstClass("first");
SecondClass second = new SecondClass();
System.out.println(second.applyFunction("second",first::addPrefix));
Você pode encontrar um exemplo no github, aqui:. Julien-Diener / MethodReference
Para simplificar, você pode usar um Runnable :
private void runCallback(Runnable callback)
{
// Run callback
callback.run();
}
Uso:
runCallback(new Runnable()
{
@Override
public void run()
{
// Running callback
}
});
Um pouco picuinhas:
Eu parecem pessoas sugerindo a criação de um objeto separado mas que parece exagero
Passar uma chamada de retorno inclui a criação de um objeto separado em praticamente qualquer linguagem OO, por isso dificilmente pode ser considerada um exagero. O que você provavelmente dizer é que em Java, ele requer que você criar uma classe separada, o que é mais detalhado (e mais recursos) do que em línguas com funções de primeira classe explícitas ou encerramentos. No entanto, classes anônimas pelo menos reduzir a verbosidade e pode ser embutido usado.
eu ainda vejo há maneira mais preferido que era o que eu estava procurando .. é basicamente derivada destas respostas, mas eu tinha de manipulá-lo para mais mais redundante e eficiente .. e eu acho que todo mundo olhando para o que i chegar a
Ao ponto ::
primeiro fazer uma interface simples
public interface myCallback {
void onSuccess();
void onError(String err);
}
Agora, para fazer este retorno prazo sempre que você deseja fazer para lidar com os resultados - mais provável após a chamada assíncrona e você quer executar algumas coisas que depende destes reuslts
// import the Interface class here
public class App {
public static void main(String[] args) {
// call your method
doSomething("list your Params", new myCallback(){
@Override
public void onSuccess() {
// no errors
System.out.println("Done");
}
@Override
public void onError(String err) {
// error happen
System.out.println(err);
}
});
}
private void doSomething(String param, // some params..
myCallback callback) {
// now call onSuccess whenever you want if results are ready
if(results_success)
callback.onSuccess();
else
callback.onError(someError);
}
}
doSomething
é a função que leva algum tempo você quer acrescentar uma chamada de retorno a ele para notificá-lo quando os resultados vieram, adicione a interface chamada de volta como um parâmetro para este método
espero que meu ponto é claro, desfrutar;)
Isto é muito fácil em Java 8 com lambdas.
public interface Callback {
void callback();
}
public class Main {
public static void main(String[] args) {
methodThatExpectsACallback(() -> System.out.println("I am the callback."));
}
private static void methodThatExpectsACallback(Callback callback){
System.out.println("I am the method.");
callback.callback();
}
}
Eu achei a idéia de implementar usando a refletir interessante biblioteca e veio com essa que eu acho que funciona muito bem. A única desvantagem é perder a verificação de tempo de compilação que você está passando parâmetros válidos.
public class CallBack {
private String methodName;
private Object scope;
public CallBack(Object scope, String methodName) {
this.methodName = methodName;
this.scope = scope;
}
public Object invoke(Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
Method method = scope.getClass().getMethod(methodName, getParameterClasses(parameters));
return method.invoke(scope, parameters);
}
private Class[] getParameterClasses(Object... parameters) {
Class[] classes = new Class[parameters.length];
for (int i=0; i < classes.length; i++) {
classes[i] = parameters[i].getClass();
}
return classes;
}
}
Você usá-lo como este
public class CallBackTest {
@Test
public void testCallBack() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
TestClass testClass = new TestClass();
CallBack callBack = new CallBack(testClass, "hello");
callBack.invoke();
callBack.invoke("Fred");
}
public class TestClass {
public void hello() {
System.out.println("Hello World");
}
public void hello(String name) {
System.out.println("Hello " + name);
}
}
}
Um método não é (ainda) um objecto de primeira classe em Java; você não pode passar um ponteiro de função como um callback. Em vez disso, criar um objeto (que geralmente implementa uma interface) que contém o método que você precisa e passar isso.
As propostas para fechamento em Java que proporcionaria o comportamento que você está procurando-foram feitas, mas nenhum será incluído na próxima versão Java 7.
Quando preciso este tipo de funcionalidade em Java, eu costumo usar o Observer padrão . Implica um objeto extra, mas eu acho que é uma maneira limpa para ir, e é um padrão amplamente compreendido, o que contribui com a legibilidade do código.
Verifique o fechamento da forma como foram implementadas na biblioteca lambdaj. Eles realmente têm um comportamento muito semelhante ao C # delegados:
Eu tentei usar java.lang.reflect para implementar 'callback', aqui está uma amostra:
package StackOverflowQ443708_JavaCallBackTest;
import java.lang.reflect.*;
import java.util.concurrent.*;
class MyTimer
{
ExecutorService EXE =
//Executors.newCachedThreadPool ();
Executors.newSingleThreadExecutor ();
public static void PrintLine ()
{
System.out.println ("--------------------------------------------------------------------------------");
}
public void SetTimer (final int timeout, final Object obj, final String methodName, final Object... args)
{
SetTimer (timeout, obj, false, methodName, args);
}
public void SetTimer (final int timeout, final Object obj, final boolean isStatic, final String methodName, final Object... args)
{
Class<?>[] argTypes = null;
if (args != null)
{
argTypes = new Class<?> [args.length];
for (int i=0; i<args.length; i++)
{
argTypes[i] = args[i].getClass ();
}
}
SetTimer (timeout, obj, isStatic, methodName, argTypes, args);
}
public void SetTimer (final int timeout, final Object obj, final String methodName, final Class<?>[] argTypes, final Object... args)
{
SetTimer (timeout, obj, false, methodName, argTypes, args);
}
public void SetTimer (final int timeout, final Object obj, final boolean isStatic, final String methodName, final Class<?>[] argTypes, final Object... args)
{
EXE.execute (
new Runnable()
{
public void run ()
{
Class<?> c;
Method method;
try
{
if (isStatic) c = (Class<?>)obj;
else c = obj.getClass ();
System.out.println ("Wait for " + timeout + " seconds to invoke " + c.getSimpleName () + "::[" + methodName + "]");
TimeUnit.SECONDS.sleep (timeout);
System.out.println ();
System.out.println ("invoking " + c.getSimpleName () + "::[" + methodName + "]...");
PrintLine ();
method = c.getDeclaredMethod (methodName, argTypes);
method.invoke (obj, args);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
PrintLine ();
}
}
}
);
}
public void ShutdownTimer ()
{
EXE.shutdown ();
}
}
public class CallBackTest
{
public void onUserTimeout ()
{
System.out.println ("onUserTimeout");
}
public void onTestEnd ()
{
System.out.println ("onTestEnd");
}
public void NullParameterTest (String sParam, int iParam)
{
System.out.println ("NullParameterTest: String parameter=" + sParam + ", int parameter=" + iParam);
}
public static void main (String[] args)
{
CallBackTest test = new CallBackTest ();
MyTimer timer = new MyTimer ();
timer.SetTimer ((int)(Math.random ()*10), test, "onUserTimeout");
timer.SetTimer ((int)(Math.random ()*10), test, "onTestEnd");
timer.SetTimer ((int)(Math.random ()*10), test, "A-Method-Which-Is-Not-Exists"); // java.lang.NoSuchMethodException
timer.SetTimer ((int)(Math.random ()*10), System.out, "println", "this is an argument of System.out.println() which is called by timer");
timer.SetTimer ((int)(Math.random ()*10), System.class, true, "currentTimeMillis");
timer.SetTimer ((int)(Math.random ()*10), System.class, true, "currentTimeMillis", "Should-Not-Pass-Arguments"); // java.lang.NoSuchMethodException
timer.SetTimer ((int)(Math.random ()*10), String.class, true, "format", "%d %X", 100, 200); // java.lang.NoSuchMethodException
timer.SetTimer ((int)(Math.random ()*10), String.class, true, "format", "%d %X", new Object[]{100, 200});
timer.SetTimer ((int)(Math.random ()*10), test, "NullParameterTest", new Class<?>[]{String.class, int.class}, null, 888);
timer.ShutdownTimer ();
}
}
Você também pode fazer theCallback
usando o padrão Delegate
:
Callback.java
public interface Callback {
void onItemSelected(int position);
}
PagerActivity.java
public class PagerActivity implements Callback {
CustomPagerAdapter mPagerAdapter;
public PagerActivity() {
mPagerAdapter = new CustomPagerAdapter(this);
}
@Override
public void onItemSelected(int position) {
// Do something
System.out.println("Item " + postion + " selected")
}
}
CustomPagerAdapter.java
public class CustomPagerAdapter {
private static final int DEFAULT_POSITION = 1;
public CustomPagerAdapter(Callback callback) {
callback.onItemSelected(DEFAULT_POSITION);
}
}
Eu comecei recentemente a fazer algo como isto:
public class Main {
@FunctionalInterface
public interface NotDotNetDelegate {
int doSomething(int a, int b);
}
public static void main(String[] args) {
// in java 8 (lambdas):
System.out.println(functionThatTakesDelegate((a, b) -> {return a*b;} , 10, 20));
}
public static int functionThatTakesDelegate(NotDotNetDelegate del, int a, int b) {
// ...
return del.doSomething(a, b);
}
}
é um pouco velho, mas mesmo assim ... Eu encontrei a resposta de Peter Wilkinson nice, exceto para o fato de que ele não funciona para tipos primitivos como int / Integer.
O problema é a .getClass()
para o parameters[i]
, que retorna por exemplo java.lang.Integer
, que por outro lado não serão corretamente interpretados por getMethod(methodName,parameters[])
(culpa de Java) ...
Eu combinei com a sugestão de Daniel Spiewak ( em sua resposta a esta ); passos para o sucesso incluíram: captura NoSuchMethodException
-> getMethods()
-> looking for the one correspondência por method.getName()
-> e depois explicitamente loop através da lista de parâmetros e aplicar solução Daniels, como identificar os jogos de tipo e os jogos de assinatura
Eu acho que usando uma classe abstrata é mais elegante, como este:
// Something.java
public abstract class Something {
public abstract void test();
public void usingCallback() {
System.out.println("This is before callback method");
test();
System.out.println("This is after callback method");
}
}
// CallbackTest.java
public class CallbackTest extends Something {
@Override
public void test() {
System.out.println("This is inside CallbackTest!");
}
public static void main(String[] args) {
CallbackTest myTest = new CallbackTest();
myTest.usingCallback();
}
}
/*
Output:
This is before callback method
This is inside CallbackTest!
This is after callback method
*/
public class HelloWorldAnonymousClasses {
//this is an interface with only one method
interface HelloWorld {
public void printSomething(String something);
}
//this is a simple function called from main()
public void sayHello() {
//this is an object with interface reference followed by the definition of the interface itself
new HelloWorld() {
public void printSomething(String something) {
System.out.println("Hello " + something);
}
}.printSomething("Abhi");
//imagine this as an object which is calling the function'printSomething()"
}
public static void main(String... args) {
HelloWorldAnonymousClasses myApp =
new HelloWorldAnonymousClasses();
myApp.sayHello();
}
}
//Output is "Hello Abhi"
Basicamente, se você quiser fazer o objeto de uma interface é não é possível, porque interface não pode ter objetos.
A opção é deixar alguma classe implementar a interface e, em seguida, chamar essa função usando o objeto dessa classe. Mas esta abordagem é realmente detalhado.
Como alternativa, escrever novo HelloWorld () (* oberserve esta é uma interface não uma classe) e depois segui-lo com o defination do próprio métodos de interface. (* Esta defination é, na realidade, a classe anônima). Então você começa a referência do objeto através do qual você pode chamar o método em si.
Criar uma Interface, e criar a mesma interface Propriedade em Callback Class.
interface dataFetchDelegate {
void didFetchdata(String data);
}
//callback class
public class BackendManager{
public dataFetchDelegate Delegate;
public void getData() {
//Do something, Http calls/ Any other work
Delegate.didFetchdata("this is callbackdata");
}
}
Agora na classe onde você quer se chamado de volta implementar o acima Criado Interface. e também passar "isto" Objeto / Referência de sua classe a ser chamado de volta.
public class Main implements dataFetchDelegate
{
public static void main( String[] args )
{
new Main().getDatafromBackend();
}
public void getDatafromBackend() {
BackendManager inc = new BackendManager();
//Pass this object as reference.in this Scenario this is Main Object
inc.Delegate = this;
//make call
inc.getData();
}
//This method is called after task/Code Completion
public void didFetchdata(String callbackData) {
// TODO Auto-generated method stub
System.out.println(callbackData);
}
}