简单的问题:如何区分默认构造函数。即:
class AClass { } // will have a default no args constructor -> public AClass() {}
来自指定的一个,例如:
class AClass {
private final int i;
public AClass() { i = 0; }
}
检查反射库提供的选项,我找不到任何可以让我区分的选项...
我主要尝试了 Class#get*Constructor(s)
提供的方法
也许我视野狭隘,我忘记了一些事情,或者我缺少另一种方法......任何帮助将不胜感激!
编辑:
这是我正在使用的方法,我需要检测这样的构造函数是否是用户定义的:
protected void adaptAfterLoading(final Class<?> loadedClass) {
Arrays.asList(loadedClass.getDeclaredConstructors()).forEach(System.out::println);
System.out.println("$$$$$$$$$$$ " + loadedClass.getDeclaredConstructors());
Arrays
.stream(loadedClass.getDeclaredConstructors())
.filter(
((Predicate<Constructor<?>>) Constructor::isSynthetic)
.negate())
.map(ConstructorRep::loadFrom)
.forEach(this::addConstructor);
}
所以...如果您想知道为什么 isSynthetic 不起作用:
来自here :
block 引用>13.1. The Form of a Binary - 7. Any constructs introduced by a Java compiler that do not have a corresponding construct in the source code must be marked as synthetic, except for default constructors, the class initialization method, and the values and valueOf methods of the Enum class.
最佳答案
根本没有办法检测到这一点,因为编译后的字节码没有区别。
具有默认构造函数的类
class AClass { } // will have a default no args constructor
隐式编译为
class AClass {
AClass() {}
}
第一种形式只是语法糖。
还有你的下一个例子
class AClass {
private final int i;
public AClass() { i = 0; }
}
可以用等效形式的默认构造函数编写
class AClass {
private final int i = 0;
}
此外,我没有看到您必须检测到这一点的用例。
关于java - 区分提供的默认无参数构造函数和声明的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54269251/