如何在 Java 中强制执行构造函数
How to enforce constructor in Java
有什么方法可以在 Java 类 中强制执行特定的构造函数?
例如,我希望所有从 Class 继承的 类 都有一个构造函数,例如 -
public classname(string s1,string s2){....}
我知道不应该避免它,因为它会导致多重继承问题。但是有办法做到吗?
抱歉,不行,您不能强制 类 只 实现特定的构造函数。
您希望只有一个构造函数,并且具有相同的签名。
这可能会在 运行 时间以昂贵的方式通过反射完成。
public BaseClass(String s, String t, int n) {
Class<?> cl = getClass();
do {
check(cl);
cl = cl.getSuperclass();
} while (cl != BaseClass.class);
}
private void check(Class<?> cl) {
if (cl.getConstructors().length != 1) {
throw new IllegalStateException("Needs only 1 constructor in: " + cl.getName());
}
try {
cl.getConstructor(String.class, String.class, int.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Constructor should have parameter types (String, String, int) in: " + cl.getName());
}
}
不可取
但是,您可以创建一个隐藏 class 层次结构的工厂。或者实际上使用单个 class 委托给您的 class 层次结构(具有您的 class 的成员)。
Java 没有设施可以直接这样做。
但是,可以使用 abstract
方法在某种程度上强制执行。
abstract class Base {
Base(String s1, String s2) {
init(s1, s2);
}
protected abstract void init(String s1, String s2);
}
class MyClass extends Base {
// Forced to do this.
MyClass() {
super("One", "Two");
}
// Forced to do this.
@Override
protected void init(String s1, String s2) {
}
}
有什么方法可以在 Java 类 中强制执行特定的构造函数?
例如,我希望所有从 Class 继承的 类 都有一个构造函数,例如 -
public classname(string s1,string s2){....}
我知道不应该避免它,因为它会导致多重继承问题。但是有办法做到吗?
抱歉,不行,您不能强制 类 只 实现特定的构造函数。
您希望只有一个构造函数,并且具有相同的签名。 这可能会在 运行 时间以昂贵的方式通过反射完成。
public BaseClass(String s, String t, int n) {
Class<?> cl = getClass();
do {
check(cl);
cl = cl.getSuperclass();
} while (cl != BaseClass.class);
}
private void check(Class<?> cl) {
if (cl.getConstructors().length != 1) {
throw new IllegalStateException("Needs only 1 constructor in: " + cl.getName());
}
try {
cl.getConstructor(String.class, String.class, int.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Constructor should have parameter types (String, String, int) in: " + cl.getName());
}
}
不可取
但是,您可以创建一个隐藏 class 层次结构的工厂。或者实际上使用单个 class 委托给您的 class 层次结构(具有您的 class 的成员)。
Java 没有设施可以直接这样做。
但是,可以使用 abstract
方法在某种程度上强制执行。
abstract class Base {
Base(String s1, String s2) {
init(s1, s2);
}
protected abstract void init(String s1, String s2);
}
class MyClass extends Base {
// Forced to do this.
MyClass() {
super("One", "Two");
}
// Forced to do this.
@Override
protected void init(String s1, String s2) {
}
}