当我在以下代码中声明数组时,我无法理解实际发生的情况.
class Type1 {
}
class Type2 extends Type1 {
public void method2() {
}
}
class Test {
public static void main(String[] args) {
Type1[] x = new Type2[2];
x[0] = new Type1(); // runtime error
x[1] = new Type2();
x[1].method2(); // syntax error
}
}
Run Code Online (Sandbox Code Playgroud)
我认为,因为数组声明的右侧是new Type2[2]数组将包含该类型的引用变量Type2.如果这是真的,那么第一个错误是有意义的,因为我不能有一个引用超类型的子类型.
但是,为什么第二个错误在那之后出现两行?method2()Type2 不知道,所以该方法是由引用变量知道的?它似乎是因为Type1不知道method2,所以这是否意味着数组由类型的引用变量组成Type1?如果这是真的,为什么第一个错误发生,因为它不再是指超类型的子类型?
另外,为什么第一个错误是运行时错误而另一个错误是语法错误?
请注意我只是在我的第二个编程课程,所以我的术语可能有点偏.
编辑:问题在这里并没有回答我的问题,因为它没有回答为什么像一个数组的元素x不能援引method2()即使的元素x的Type 2.我的问题因此而有所不同,因为我的问题也询问为什么第二个错误也会发生时出现第一个错误(为什么一个元素x不能引用该类型的对象Type1 …
我正在尝试创建一个方法invokeMethod(String methodName, Object...args),该方法从当前实例上的超类调用方法。我尝试了以下实现。
public void invokeMethod(String methodName, Object...args) {
//Array to hold the classes of the arguments
Class<?>[] classes = new Class<?>[args.length];
//Initialize each class in the array to the class of each argument
for(int i = 0; i < args.length; i++)
classes[i] = args[i].getClass();
try {
//find the method
Method m = this.getClass().getMethod(methodName, classes);
//invoke the method
m.invoke(this, args);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
这个实现的问题是,如果我尝试调用一个带有原始参数的方法,我会得到一个,NoSuchMethodException …
我在以下代码中遇到了编译错误,但我不知道如何解决。
public class Test throws IOException{
public static void main(String[] args) {
String path = "document.txt";
File file = new File(path);
Files.readString(file.toPath()); //cannot find symbol method readString(java.nio.file.Path)
}
}
Run Code Online (Sandbox Code Playgroud)
但我明白了
错误:(
8、14 )Java:找不到符号符号:方法readString(java.nio.file.Path)
位置:类java.nio.file.Files
有很多事情要注意。
readString(Path)中java.nio.file.Files。如果我要尝试size(Path)(中的另一种方法java.nio.file.Files),它可以工作此代码在intelliJ中不起作用,但在eclipse中起作用
如果我在intelliJ中创建了一个新项目,但在从github克隆的当前Maven项目中却没有,则此代码有效
Test.java