我有两套讲义。人们将构造函数称为方法的一种形式。另一组注释声称构造函数不是方法。
我个人觉得构造函数不是方法。但是我在构造函数
上使用术语invoke
是否正确?
我的问题是:我们可以调用 java 方法。但我说“调用构造函数”正确吗?
<小时/>我访问了这个网站:http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html
在构造函数上使用术语invoke
看起来不合适?
最佳答案
Merriam Webster describes invoke
like this:
: to mention (someone or something) in an attempt to make people feel a certain way or have a certain idea in their mind
: to refer to (something) in support of your ideas
: to make use of (a law, a right, etc.)
所以是的,我想说你可以像调用方法一样调用构造函数。但如 the java specifcation说
Constructors are never invoked by method invocation expressions
因此只能通过创建对象来调用构造函数:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class InvokeConstructor {
public InvokeConstructor() {
System.out.println("constructor1");
}
public InvokeConstructor(final boolean unused) {
System.out.println("constructor2");
}
public static void main(String[] args) {
new InvokeConstructor();
new InvokeConstructor(false);
// And using reflection:
try {
Constructor<InvokeConstructor> constructor1 = InvokeConstructor.class.getConstructor();
constructor1.newInstance();
Constructor<InvokeConstructor> constructor2 = InvokeConstructor.class.getConstructor(Boolean.TYPE);
constructor2.newInstance(Boolean.FALSE);
} catch (NoSuchMethodException e) {
e.printStackTrace(); // TODO: implement catch
} catch (InvocationTargetException e) {
e.printStackTrace(); // TODO: implement catch
} catch (InstantiationException e) {
e.printStackTrace(); // TODO: implement catch
} catch (IllegalAccessException e) {
e.printStackTrace(); // TODO: implement catch
}
}
}
关于java - 我们可以调用类构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26693667/