• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to call factory method using Reflection  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public interface ES
{

Factory Factory = (Factory) MyFactory.INSTANCE;

interface Factory
{
ES create(String a, String b);
}
}

public class MyFactory implements ES.Factory
{

public static MyFactory INSTANCE = new MyFactory();

public ES create(String a, String b)
{
return create(a, b);
}

public ES create(a, b){
System.out.println("&&&&&&&&&&&&&&&&& do something");
}

I want to invoke :

ES es = ES.Factory.create(a,b);

using reflection.

I tried two ways:

First Way: Get the field and try to invoke the method on the filed like following:
String className = "EC";
Class classDefinition = Class.forName(className);
Field factory = classDefinition.getField("Factory");
Class factoryCls = factory.getType();
Class[] par=new Class[2];
par[0]=java.lang.String.class;
par[1]=String.class;
Method method = factoryCls.getMethod("create",par);
ES es = (ES)method.invoke(factoryCls,input);

Second Way:

Class factoryClsImpl = Class.forName("MyFactory");
Class[] par=new Class[2];
par[0]=java.lang.String.class;
par[1]=String.class;
Method method2 = factoryClsImpl.getMethod("create",par);
String[] input2={componentKindQName,componentQName};
es = (ES)method2.invoke(factoryClsImpl,input2);
 
author and iconoclast
Sheriff
Posts: 24218
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

We have a strict policy on display names, which must be a real first and last name with a space between.

Please go here and fix your display name up, pronto. Thanks, pardner!

Now, as to your question: your example code is broken in so many ways, it's hard to see exactly what problems you might be having. Not only is the "target" code broken, but the example reflection code makes very obvious mistakes like using "EC" instead of "ES". So it's really hard to give much advice here. Neither of these code samples looks unreasonable, but of course it's important to get all the little details right.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!