A类:
public class A {
public B b;
public A(String s) {
b = new B(s);
}
}
B组:
public class B {
String s;
public B(String s) {
this.s = s;
}
public void printB() {
System.out.println(this.s);
}
}
所以我想在java中使用反射来创建类A并使用他的公共成员B,以便使用来自客户端的给定字符串的反射来运行printB方法' printB'
我该怎么做?
答案 0 :(得分:2)
我不确定你为什么要这样做,但作为一个概念证明...
package myPackage;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
try {
Class clazz = Class.forName("myPackage.Test$a");
Constructor con = clazz.getConstructor(String.class);
Object instanceOfA = con.newInstance("A value");
Field bField = clazz.getField("b");
Object instanceOfB = bField.get(instanceOfA);
Method printBMethod = instanceOfB.getClass().getMethod("printB");
printBMethod.invoke(instanceOfB);
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchFieldException ex) {
ex.printStackTrace();
}
}
public static class a {
public B b;
public a(String s) {
b = new B(s);
}
}
public static class B {
String s;
public B(String s) {
this.s = s;
}
public void printB() {
System.out.println(this.s);
}
}
}