反射地基于静态类生成可实例化的类 [英] Generate an instantiable class based on a static class reflectively
本文介绍了反射地基于静态类生成可实例化的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以(假设使用反射功能)创建一个类,其方法名称与 java.lang.Math
相同,并且每个方法都将其转发给 Math
吗?
Can I (using reflection I presume?) create a class with all the same method names as java.lang.Math
and each method just forwards it to Math
?
例如
public class MyMath {
public MyMath() {}
public double abs(double a) {
return Math.abs(a);
}
public float abs(float a) {
return Math.abs(a);
}
public int abs(int a) {
return Math.abs(a);
}
...
public double acos(double a) {
return Math.acos(a);
}
...
我该如何以编程方式生成它?
How could I generate this programmatically?
推荐答案
您可以通过反射来获得Math类的实例:
You can do this with reflection to get an instance of class Math:
try {
Constructor[] cs = Math.class.getDeclaredConstructors();
cs[0].setAccessible(true);
Math m = (Math) cs[0].newInstance();
//e.g.
System.out.println(m.sqrt(16));
}
catch (Exception e) {
e.printStackTrace();
}
这是否明智的做法是另一个问题.
Whether this is a sensible thing to do is another question.
这篇关于反射地基于静态类生成可实例化的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文