java class作为参数_如何在Java中传递一个类作为参数?

public void foo(Class c){ try { Object ob = c.newInstance(); } catch (InstantiationException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } }

以下是Reflection API的一些很好的例子

如何使用reflection调用方法

import java.lang.reflect.*; public class method2 { public int add(int a, int b) { return a + b; } public static void main(String args[]) { try { Class cls = Class.forName("method2"); Class partypes[] = new Class[2]; partypes[0] = Integer.TYPE; partypes[1] = Integer.TYPE; Method meth = cls.getMethod( "add", partypes); method2 methobj = new method2(); Object arglist[] = new Object[2]; arglist[0] = new Integer(37); arglist[1] = new Integer(47); Object retobj = meth.invoke(methobj, arglist); Integer retval = (Integer)retobj; System.out.println(retval.intValue()); } catch (Throwable e) { System.err.println(e); } } }

另见

Javareflection

public void callingMethod(Class neededClass) { //Put your codes here }

要调用该方法,可以这样调用它:

callingMethod(ClassBeingCalled.class);

使用

void callClass(Class classObject) { //do something with class }

一个Class也是一个Java对象,所以你可以使用它的types来引用它。

从官方文档中了解更多信息。

这种事情不容易。 这是一个调用静态方法的方法:

public static Object callStaticMethod( // class that contains the static method final Class> clazz, // method name final String methodName, // optional method parameters final Object... parameters) throws Exception{ for(final Method method : clazz.getMethods()){ if(method.getName().equals(methodName)){ final Class>[] paramTypes = method.getParameterTypes(); if(parameters.length != paramTypes.length){ continue; } boolean compatible = true; for(int i = 0; i < paramTypes.length; i++){ final Class> paramType = paramTypes[i]; final Object param = parameters[i]; if(param != null && !paramType.isInstance(param)){ compatible = false; break; } } if(compatible){ return method.invoke(/* static invocation */null, parameters); } } } throw new NoSuchMethodException(methodName); }

更新:等等,我刚刚在问题上看到了gwt标签。 你不能在GWT中使用reflection

我不确定你想要完成什么,但是你可能要考虑,通过一个class级可能不是你真正需要做的事情。 在许多情况下,像这样处理类很容易被封装在某种types的工厂模式中,并且通过一个接口来完成。 这是几十篇关于这种模式的文章之一: http : //today.java.net/pub/a/today/2005/03/09/factory.html

在工厂内使用类可以通过多种方式来完成,最显着的是通过一个包含实现所需接口的类的名称的configuration文件。 然后工厂可以从类path中find该类,并将其构造为指定接口的对象。

正如你所说,GWT不支持反思。 您应该使用延迟绑定而不是reflection或第三方库(如gwt-ent)来reflectionsuppport在gwt层。

Se这些: http : //download.oracle.com/javase/tutorial/extra/generics/methods.html

这里是模板方法的解释。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值