用Javareflection如何实例化一个新对象,然后调用一个方法呢?

我是Java的新手,我正面临一个反思问题。

假设我必须在类Foobar的实例上动态调用方法fooMethod

到目前为止,我得到了Foobar一个实例:

 Object instance = Class.forName("Foobar").newInstance(); 

假设我知道在这个对象上有一个方法fooMethod (我甚至可以用Class.forName("Foobar").getDeclaredMethods()来检查它fooMethod Class.forName("Foobar").getDeclaredMethods() ),请问如何调用它?

 Method method = getClass().getDeclaredMethod("methodName"); m.invoke(obj); 

这是在方法没有参数的情况下。 如果有,则将参数类型作为参数附加到此方法。 obj是您调用方法的对象。

请参阅java.lang.Class文档

纯粹反思: Method.invoke 。 另一种解决方案是要求您reflection创建的项目实现已知接口并转换为此接口并正常使用。

后者通常用于“插件”,前者不经常使用。

你可以在这里阅读它。

至于您之后的代码是这样的(来自相同的资源):

 Method[] allMethods = c.getDeclaredMethods(); for (Method m : allMethods) { String mname = m.getName(); if (!mname.startsWith("test") || (m.getGenericReturnType() != boolean.class)) { continue; } Type[] pType = m.getGenericParameterTypes(); if ((pType.length != 1) || Locale.class.isAssignableFrom(pType[0].getClass())) { continue; } out.format("invoking %s()%n", mname); try { m.setAccessible(true); Object o = m.invoke(t, new Locale(args[1], args[2], args[3])); out.format("%s() returned %b%n", mname, (Boolean) o); // Handle any exceptions thrown by method to be invoked. } catch (InvocationTargetException x) { Throwable cause = x.getCause(); err.format("invocation of %s failed: %s%n", mname, cause.getMessage()); } 

你可以使用反思

样本class

 package com.google.util; Class Maths { public Integer doubleIt(Integer a) { return a*2; } } 

并使用像这样的SomeThing-

步骤1 : – 将给定输入名称的类加载为String

 Class obj=Class.forName("Complete_ClassName_including_package"); //like:- Class obj=Class.forName("com.google.util.Maths"); 

第2步 : – 获取具有给定名称和参数类型的方法

 Method method=obj.getMethod("NameOfMthodToInvoke", arguments); //arguments need to be like- java.lang.Integer.class //like:- Method method=obj.getMethod("doubleIt",java.lang.Integer.class); 

步骤3 : – 调用方法通过传递Object和参数的实例

 Object obj2= method.invoke(obj.newInstance(), id); //like :- method.invoke(obj.newInstance(), 45); 

你也可以做第2步

(当你不知道一个类中存在特定方法时 ,你通过循环方法的数组检查所有方法)

 Method[] methods=obj.getMethods(); Method method=null; for(int i=0;i<methods.length();i++) { if(method[1].getName().equals("methodNameWeAreExpecting")) { method=method[i]; } } 

这应该适合你:

 ((Foobar)instance).fooMethod()