gpt4 book ai didi

Java 反射 : Create an implementing class

转载 作者:IT老高 更新时间:2023-10-28 13:52:12 25 4
gpt4 key购买 nike

Class someInterface = Class.fromName("some.package.SomeInterface");

我现在如何创建一个实现 someInterface 的新类?

我需要创建一个新类,并将其传递给需要 SomeInterface 作为参数的函数。

最佳答案

很容易,java.lang.reflect.Proxy来救援!

完整的工作示例:

interface IRobot {

String Name();

String Name(String title);

void Talk();

void Talk(String stuff);

void Talk(int stuff);

void Talk(String stuff, int more_stuff);

void Talk(int stuff, int more_stuff);

void Talk(int stuff, String more_stuff);
}

public class ProxyTest {
public static void main(String args[]) {
IRobot robot = (IRobot) java.lang.reflect.Proxy.newProxyInstance(
IRobot.class.getClassLoader(),
new java.lang.Class[] { IRobot.class },
new java.lang.reflect.InvocationHandler() {

@Override
public Object invoke(Object proxy, java.lang.reflect.Method method, Object[] args) throws java.lang.Throwable {
String method_name = method.getName();
Class<?>[] classes = method.getParameterTypes();

if (method_name.equals("Name")) {
if (args == null) {
return "Mr IRobot";
} else {
return args[0] + " IRobot";
}
} else if (method_name.equals("Talk")) {
switch (classes.length) {
case 0:
System.out.println("Hello");
break;
case 1:
if (classes[0] == int.class) {
System.out.println("Hi. Int: " + args[0]);
} else {
System.out.println("Hi. String: " + args[0]);
}
break;
case 2:
if (classes[0] == String.class) {
System.out.println("Hi. String: " + args[0] + ". Int: " + args[1]);
} else {
if (classes[1] == String.class) {
System.out.println("Hi. int: " + args[0] + ". String: " + args[1]);
} else {
System.out.println("Hi. int: " + args[0] + ". Int: " + args[1]);
}
}
break;
}
}
return null;
}
});

System.out.println(robot.Name());
System.out.println(robot.Name("Dr"));
robot.Talk();
robot.Talk("stuff");
robot.Talk(100);
robot.Talk("stuff", 200);
robot.Talk(300, 400);
robot.Talk(500, "stuff");
}
}

关于Java 反射 : Create an implementing class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1082850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com