如果obj是个内部类,那么传递的参数只能是声明为final的, 比如: public A(final int n) { obj o=new obj(); o.f(n); } 而那个参数n也必须在A方法的外部声明为final的 比如: final int m; A(m);如果obj不是内部类,怎样都可以
如果obj是动态的,那就需要用反射机制了吧 那部分好复杂,高手来讲讲!
zt一个sample: Reflection is used to invoke a method when name of the method is supplied at run time. This tip will show a sample code to do that.import java.lang.reflect.Method;public class RunMthdRef { public int add(int a, int b) { return a+b; } public int sub(int a, int b) { return a-b; } public int mul(int a, int b) { return a*b; } public int div(int a, int b) { return a/b; } public static void main(String[] args) { try { Integer[] input={new Integer(2),new Integer(6)}; Class cl=Class.forName("RunMthdRef"); Class[] par=new Class[2]; par[0]=Integer.TYPE; par[1]=Integer.TYPE; Method mthd=cl.getMethod("add",par); Integer output=(Integer)mthd.invoke(new RunMthdRef(),input); System.out.println(output.intValue()); } catch (Exception e) { e.printStackTrace(); } } }
大概是这样吧: public Object A(Object obj,Method f,Object[] args) { //里面是好多用到java.lang.reflect这个包中类的代码,看看API或许你就会了 }
反射式解决办法之一,但是这样耦合度太高(除非+配置文件,如开源项目多采用这种),我还是认为增加一个接口(超类),它是所有obj对象 类的超类 ,超类中写一个所有类都要实现的方法g(), 而子类都必须实现g(),g()调用你自己写的各种不同的方法如你说的f(),或是h(); 比如 public interface Super { public void g();}public class SubClassB implements Super { public void f(){做一些操作} public void g(){f(); } }public class SubClassC implements Super { public void h(){做一些操作} public void g(){h();n(); } public void n(){做一些操作} }那么A方法就可以这样了 public void A(Suber s) { if(s!=null) { s.g(); }}
比如:
public A(final int n)
{
obj o=new obj();
o.f(n);
}
而那个参数n也必须在A方法的外部声明为final的
比如:
final int m;
A(m);如果obj不是内部类,怎样都可以
那部分好复杂,高手来讲讲!
Reflection is used to invoke a method when name of the method is supplied at run time. This tip will show a sample code to do that.import java.lang.reflect.Method;public class RunMthdRef {
public int add(int a, int b) {
return a+b;
} public int sub(int a, int b) {
return a-b;
} public int mul(int a, int b) {
return a*b;
} public int div(int a, int b) {
return a/b;
} public static void main(String[] args) {
try {
Integer[] input={new Integer(2),new Integer(6)};
Class cl=Class.forName("RunMthdRef");
Class[] par=new Class[2];
par[0]=Integer.TYPE;
par[1]=Integer.TYPE;
Method mthd=cl.getMethod("add",par);
Integer output=(Integer)mthd.invoke(new RunMthdRef(),input);
System.out.println(output.intValue());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public Object A(Object obj,Method f,Object[] args)
{
//里面是好多用到java.lang.reflect这个包中类的代码,看看API或许你就会了
}
而子类都必须实现g(),g()调用你自己写的各种不同的方法如你说的f(),或是h();
比如
public interface Super
{
public void g();}public class SubClassB implements Super
{
public void f(){做一些操作}
public void g(){f(); }
}public class SubClassC implements Super
{
public void h(){做一些操作}
public void g(){h();n(); }
public void n(){做一些操作}
}那么A方法就可以这样了
public void A(Suber s)
{
if(s!=null)
{
s.g();
}}
高手!