开发者

Java Interface Reflection Alternatives

I am developing an application that makes use of the Java Interface as more than a Java interface, i.e., During runtime, the user should be able to list the available methods within the interface class, which may be anything:

private Class<? extends BaseInterface> interfaceClass.

At runtime, I would like to enum the available methods, and then based on what the user chooses, invoke some method.

My question is: Does the Java "Interface" architecture provide any method for me to peek and invoke methods without using the Reflection API?

I wish there were something like this (Maybe there is):

private Interface<? extends BaseInterface> interfaceAPI;

public void someMethod(){
 interfaceAPI.listMethods();
 interfaceAPI.getAnnotations();
}

Mayb开发者_开发知识库e there is some way to use Type Generics to accomplish what I want?

Thanks,

Phaedrus


This is exactly what Reflection was built for.


Take a look at Apache Commons BeanUtils. It's an excellent library for programmatically discovering an object's methods and properties easily (i.e. without writing low-level reflection code). I've used it on several projects. It also provides an easier API for accessing those object members once they're discovered. PropertyUtils and MethodUtils are good places to start.


My question is: Does the Java "Interface" architecture provide any method for me to peek and invoke methods without using the Reflection API?

a) No, reflection is the only way to do that

b) don't do that at all. If you want a dynamic language, use Groovy. It's syntax is (can be) almost identical to java, but it has most of this functionality built in already. (Many other languages will also work, but Groovy is closest to Java when comparing the syntax)


Reflection is the only way to list methods of an arbitrary object. Well, parsing the bytecode also works, but it's tedious.


Unfortunately it looks like reflection is the only way to go. Unfortunate because reflection is not only slower but programming and maintaining is a hassle. So I suggest you use apache bean util library. (specifically methodutils.)


Although there's no way around reflection here, it can be made relatively painless if you use annotations to mark your callable methods. An example of this approach at work is the javax.jws annotation set for webservices. The ideas used there can be really useful, you can define a display name for each of your methods/parameters for example.


Reflection with Annotations is working Nicely

for (Method m : interfaceClass.getMethods()) {
         if (m.isAnnotationPresent(UIf.class)) {
            UIf x = m.getAnnotation(UIf.class);
            addDefinedCommand( new CommandDef(
                    interfaceClass, 
                    u, 
                    x.name().isEmpty() ? m.getName() : x.name(), 
                    x.description()) 
            );
         }
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜