Groovy 'as' keyword to implement 2+ interfaces

◇◆丶佛笑我妖孽 提交于 2019-12-22 11:28:46

问题


I would like to implement a Glazed List that has both an AdvancedTableFormat and WritableTableFormat interface.

I am reading here: http://www.jroller.com/aalmiray/entry/glazedlists_groovy_not_your_regular

and for one interface it seems this is possible in Groovy with the "as" keyword:

# return new EventTableModel(linksList, [  
#       getColumnCount: {columnNames.size()},  
#       getColumnName: {index -> columnNames[index]},  
#       getColumnValue: {object, index ->  
#          object."${columnNames[index].toLowerCase()}"  
#       }] as TableFormat)

Is it somehow possible to do this for two interfaces? If so how?

Thank you!

Misha


回答1:


You can create a new interface that extends the two interfaces you are interested in.

interface PersonalizedTableFormat extends AdvancedTableFormat, WriteableTableFormat {
}

You can cast the object you return to the new interface.

return object as PersonalizedTableFormat;



回答2:


The "as" keyword is just a fancy way of invoking Groovy's asType(Class) method, which takes only a single Class as an argument. Therefore you can't directly use "as" with more than one interface (unless you take frm's approach and combine the interfaces in one super interface).




回答3:


I wonder if you want to implement 2 or more interfaces on the fly, and do not prefer to 'hard code' like
interface abc extends aaa,bbb,ccc {}?

May be you can try the following code:

import static java.util.Collections.sort
def doClose(Closeable c){
    c.close();
}
def o = new Object()
o.metaClass{
    compare{Object a,String b-> return a.size() - b.size()};
    close{println 'Lights out - I am closing'};
}
o = new ProxyGenerator().instantiateDelegate([Comparator, Closeable], o)
def items = ['a', 'bbb', 'cc']
sort(items, o);
println items;
doClose(o);
println o.class.getInterfaces();


来源:https://stackoverflow.com/questions/3078115/groovy-as-keyword-to-implement-2-interfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!