Java 如何将变量传递给新的 Runnable 声明?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4297261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how can I pass a variable into a new Runnable declaration?
提问by Jimmy
I have the following :
我有以下几点:
Runnable done = new Runnable()
{
public void run()
{
System.out.println("Hello");
}
};
And then in my Android activity I'll call something like :
然后在我的 Android 活动中,我会调用类似的东西:
runOnUIThread(done);
Which I then call. However, I want that "Hello"
not to be hardcoded, so I can pass it in. Otherwise I'll have to have one of these declarations for every String I want to print.
然后我称之为。但是,我希望"Hello"
不要对其进行硬编码,因此我可以将其传入。否则,我必须为要打印的每个字符串使用这些声明之一。
(This is actually an android question, but slimmed it down to basic Java so its easier to answer)
(这实际上是一个 android 问题,但将其简化为基本的 Java,因此更容易回答)
Thanks
谢谢
采纳答案by Bart van Heukelom
final String hello = whereverItsComingFrom;
Runnable done = new Runnable()
{
public void run()
{
System.out.println(hello);
}
};
回答by Ralph
In Java (and I believe it is the same in Android too), you can use a anonymous inner class, like suggested by Bart van Heukelom. This solution has the advantage that have to write less code, and you could access fields and methods ouf the outer class.
在 Java 中(我相信在 Android 中也是如此),您可以使用匿名内部类,就像 Bart van Heukelom 所建议的那样。该解决方案的优点是必须编写更少的代码,并且您可以访问外部类的字段和方法。
But it has 2 drawbacks:
但它有两个缺点:
the variable "hello" has to be final,
the anonymous class has a internal reference to the outer class instance - this means the outer class being retained when it would otherwise be eligible for garbage collection. @See: Effective Java [Joshua Bloch], Item 22: Favor static member classes over nonstatic
变量“hello”必须是最终的,
匿名类有一个对外部类实例的内部引用——这意味着外部类在它有资格进行垃圾收集时被保留。@See:Effective Java [Joshua Bloch],第 22 条:优先使用静态成员类而不是非静态成员类
And in my humble opinion, it is bad practice to parametrize a class instance in this way.
以我的拙见,以这种方式参数化类实例是不好的做法。
So I believe, as long as you do not need to access methods and fields of the outer class, it is better to write an specific class for this task and make it a staticmember class.
所以我相信,只要你不需要访问外部类的方法和字段,最好为此任务编写一个特定的类,并使其成为静态成员类。
class Demo {
...
private static class MyRunnable implements Runnable {
private final String message;
MyRunnable(final String message) {
this.message = message;
}
public void run() {
System.out.println(message);
}
}
public void startThread() {
MyRunnable myRunnable = new MyRunnable("Hello");
runOnUIThread(myRunnable);
}
...
}