[英]Invoking a method of an anonymous class without reflection in java
I want to do something like this 我想做这样的事情
static <T> T mine()
{
return new Object(){void hello(){}};
}
so that I can do this 这样我就可以做到
mine().hello();
the intend is to do something like this 打算做这样的事情
mine.hello().hi().bye();
so either I declare classes each with 1 method hello,hi,bye and than return there instances or somehow I could return an anonymous class(with newly defined method) form each method like above. 所以我要么用1个方法hello,hi,bye声明类,然后返回实例,要么以某种方式从上述每个方法返回一个匿名类(具有新定义的方法)。 so that I dont have to write lot of classes.
这样我就不必写很多类了。
Like it I can do 喜欢它我可以做
static <T> T tunnel(T t)
{
return t;
}
tunnel(new Object()
{
void hello()
{
System.out.println("hello");
}
}).hello();
but its of no use, I want to return anonymous object(created in tunnel itself) from tunnel , instead of returning passed argument 但它没有用,我想从tunnel返回匿名对象(在Tunnel本身中创建),而不是返回传递的参数
You probably want a fluent class. 您可能想要流利的课堂。 Something like
就像是
public class MyFluentClass {
public MyFluentClass methodOne() {
// do something
return this;
}
public MyFluentClass methodTwo() {
// do something
return this;
}
}
And then in your main method: 然后在您的主要方法中:
MyFluentClass myFuent = new MyFluentClass();
myFluent.methodOne().methodTwo();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.