繁体   English   中英

无法访问同一包中另一个类的方法

[英]Access to method of another class in the same package is not possible

我无法访问同一程序包中的类的静态方法。 我在自动完成中显示了类名,但是该方法不起作用。

我已经尝试过intellij的以下功能,但未成功。

“文件”>“使缓存无效/重新启动”>“使无效并重新启动”

方法:

package de.elektriker_lifestyle.reducedcoffee;

import java.util.List;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import com.opencsv.*;

public class csvReader {

    private static final char SEPARATOR = ',';

    public static void updateCSV(String input, String output, String  replace, int row, int col) throws IOException {

        CSVReader reader = new CSVReader(new FileReader(input),SEPARATOR);
        List<String[]> csvBody = reader.readAll();
        csvBody.get(row)[col]=replace;
        reader.close();

        CSVWriter writer = new CSVWriter(new FileWriter(output),SEPARATOR,' ');
        writer.writeAll(csvBody);
        writer.flush();
        writer.close();
    }



}

在这里我要使用该方法:

package de.elektriker_lifestyle.reducedcoffee;
public class test {
    csvReader.updateCSV(...);
}

屏幕截图:

出现以下错误“无法解析符号'updateCSV'”。

该代码不是有效的Java,您不能从类的主体中调用方法,方法调用必须是某种初始化程序(例如静态字段初始化程序或静态块)或方法的一部分。

public class test {
    csvReader.updateCSV(...);
}

您需要使用所有必需的参数来调用静态方法csvReader.updateCSV:

csvReader.updateCSV("1", "2", "3", 4, 5);

使用以下代码作为指导:

import java.util.List;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;

public class csvReader {

    private static final char SEPARATOR = ',';

    public static void updateCSV(String input, String output, String  replace, int row, int col) throws IOException {

        CSVReader reader = new CSVReader(new FileReader(input),SEPARATOR);
        List<String[]> csvBody = reader.readAll();
        csvBody.get(row)[col]=replace;
        reader.close();

        CSVWriter writer = new CSVWriter(new FileWriter(output),SEPARATOR,' ');
        writer.writeAll(csvBody);
        writer.flush();
        writer.close();
    }

    public static void main(String[] args) throws IOException {
            csvReader.updateCSV("1", "2", "3", 4, 5);

    }

}

如先前的回答所述,您不能在类的主体中调用该方法,所有方法的执行都应在另一个方法内部进行,直到主方法为止。

另外,您正在进行的调用缺少方法声明中的某些参数。

最后,如果您希望始终在类上执行静态方法,则应在类构造函数上执行该方法:

public class test {

   public test () {
    csvReader.updateCSV(...);
   }
}

这样,每次创建测试对象时,您的静态方法都将被执行。

在公共类test上方的测试类中导入de.elektriker_lifestyle.reducedcoffee.csvReader.java {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM