题
有没有办法通过一个回电话的功能在Java方法?
行为我想模仿。净委托被传递到一个功能。
我见过有人建议创建一个独立的对象,但似乎矫枉过正,但是我知道有时候,矫枉过正的唯一方法是,要做的事情。
解决方案
如果你说的是财产以后等。净匿名的委托,我认为Java是匿名的流可以使用。
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));
}
}
其他提示
由于Java8,有lambda和方法参考:
例如,可以让定义:
public class FirstClass {
String prefix;
public FirstClass(String prefix){
this.prefix = prefix;
}
public String addPrefix(String suffix){
return prefix +":"+suffix;
}
}
和
import java.util.function.Function;
public class SecondClass {
public String applyFunction(String name, Function<String,String> function){
return function.apply(name);
}
}
然后你可以这样做:
FirstClass first = new FirstClass("first");
SecondClass second = new SecondClass();
System.out.println(second.applyFunction("second",first::addPrefix));
你可以找到一个例子审查,在这里: julien-diener/MethodReference.
为了简单起见,可以使用 可运行的:
private void runCallback(Runnable callback)
{
// Run callback
callback.run();
}
使用:
runCallback(new Runnable()
{
@Override
public void run()
{
// Running callback
}
});
一点吹毛求疵:
我似乎人们建议创建一个 独立的对象,但似乎 矫枉过正
通过回调包括创建一个单独的对象几乎任何OO语言,所以它可以很难被认为是大材小用。什么你大概意思是,它需要创建一个单独的类,它更详细的(和更多的资源密集型)于在语言具有明确的一类功能或关闭。然而,匿名的类别至少减少的详细程度和可以使用内联。
但我看到的是最佳的方式,这是我一直在寻找什么..它基本上源自这些答案,但我不得不操纵更多的冗余和效率的.. 我想每个人都在寻找什么,我来了
要点::
第一次使一个接口 这么简单
public interface myCallback {
void onSuccess();
void onError(String err);
}
现在使这种回运行时,任何你想要做,以处理的成果 更可能的后的异步呼叫,你想一些东西,这取决于这些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
是的功能需要一些时间,你想增加一个回来到时通知你的结果出来,加上回电话的接口,作为一个参数,这种方法
希望我的观点是明确的,享;)
这是非常容易在Java8lambda.
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();
}
}
我发现这个想法的实施使用反映库的有趣和想出了这个这个我认为效果相当不错。只有下面是丧失的编制时间检查,你是通过有效的参数。
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;
}
}
你用这样
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);
}
}
}
一个方法是没有(尚未)第一类对象在Java;你可以不通过一种功能的指针作为回调。相反,创建一个目的(通常实现一个接口),其中包含的方法需要,并通过。
提议关闭Java—这将可提供行为正在寻找的—已经做出,但其中任何一项事业都不会被包括在即将到来的Java7释放。
当我需要这种功能在爪哇,我通常会使用 观察员的模式.它意味着一个额外的对象,但我认为这是一个干净的路要走,并且被广泛理解的模式,这有助于代码的可读性。
检查封闭装置如何,他们已经实现的lambdaj图书馆。他们实际上有一个行为非常相似C#代表:
我试图使用java。郎。反映到实施'callback',这是一个示例:
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 ();
}
}
你还可以做的Callback
使用 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);
}
}
我最近开始做这样的事情:
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);
}
}
这是一个有点旧,但...我找到了答案的彼得*威尔金森很好除了一个事实,即它不工作的基本类型喜欢int/整数。问题是 .getClass()
的 parameters[i]
, 返回的实例 java.lang.Integer
, ,而另一方面将不能正确解释 getMethod(methodName,parameters[])
(Java的错)...
我结合这项建议的丹尼尔*Spiewak(在他回答这个);成功的步骤包括:捕捉 NoSuchMethodException
-> getMethods()
->寻找匹配的一个通过 method.getName()
->,然后明确的循环,通过该列表中的参数和应用丹尼尔斯的解决方案,这种识别类型的匹配,并签署相匹配。
我认为使用一个抽象的类是更优雅,这样的:
// 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"
基本上如果你想要做的目的一个接口,这是 不可能的,因为接口不具有对象。
选项就是让某些类实现接口,然后调功能,使用对象的那类。但是,这种方法是真详细。
或者,写入新的案()(*oberserve这是一个接口不一类),然后按照它与该定义的界面方法本身。(*这一定义是在现实中的匿名类)。然后你得到的对象,参考通过它可以调用该方法本身。
创建一个接口,并创建的接口相同的财产中回调类。
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");
}
}
现在在班,你想要得到回执行上述创建的接口。并且还通过"本"的对象参考类被调回。
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);
}
}