我有一个不断变化的 xml 架构(使用 trang 自动生成)。这些变化不是很精细。此架构中仅添加或删除了一些元素。从这个模式中,我正在生成 java 类(使用 cxf),通过这些类我将解码 xml 文档。
随着架构的变化,我的自动生成的 java 类也会发生变化。同样,与模式一样,java 类的变化不是很大。例如,如果一个元素说 elemA
被添加到模式中;一些相关的函数说 getElemA()
和 setElemA()
被添加到自动生成的 java 类中。
现在我将如何确保这些自动生成的类中存在特定的函数?一种解决方案是手写模式,以便覆盖 xml 的所有可能元素。这就是我最终要做的。但是目前我还没有固定xml文件的格式。
更新:
getElemA()
方法有可能在自动生成的类中定义。我无法控制这些类的自动生成。但是在我的主课中,如果有以下代码,
If method getElemA exists then
ElemA elemA = getElemA()
此代码将始终存在于我的主类中。如果在自动生成的类之一中生成方法 getElemA()
则没有问题。但是如果没有生成这个方法,那么编译器就会提示这个方法在任何类中都不存在。
有什么方法可以让编译器在编译时不提示这个函数?
最佳答案
@missingfaktor 提到了一种方法,下面是另一种方法(如果您知道 api 的名称和参数)。
假设您有一种不带参数的方法:
Method methodToFind = null;
try {
methodToFind = YouClassName.class.getMethod("myMethodToFind", (Class<?>[]) null);
} catch (NoSuchMethodException | SecurityException e) {
// Your exception handling goes here
}
如果存在就调用它:
if(methodToFind == null) {
// Method not found.
} else {
// Method found. You can invoke the method like
methodToFind.invoke(<object_on_which_to_call_the_method>, (Object[]) null);
}
假设您有一种方法采用原生 int
args:
Method methodToFind = null;
methodToFind = YouClassName.class.getMethod("myMethodToFind", new Class[] { int.class });
如果存在就调用它:
if(methodToFind == null) {
// Method not found.
} else {
// Method found. You can invoke the method like
methodToFind.invoke(<object_on_which_to_call_the_method>, invoke(this,
Integer.valueOf(10)));
}
假设您有一种方法采用盒装 Integer
参数:
Method methodToFind = null;
methodToFind = YouClassName.class.getMethod("myMethodToFind", new Class[] { Integer.class });
如果存在就调用它:
if(methodToFind == null) {
// Method not found.
} else {
// Method found. You can invoke the method like
methodToFind.invoke(<object_on_which_to_call_the_method>, invoke(this,
Integer.valueOf(10)));
}
使用上面的soln调用方法不会给你编译错误。 根据@Foumpie 更新
关于java - 如何检查java类中是否有特定的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10876552/