简体   繁体   中英

getDeclaredMethod in Java Fails

I have a batch app which uses a file input with the method names and then the names are used to execute a method with the same name by design.

eg File has getTemperature and then getTemperature is executed in the class.

I am using the following Java:

java version "1.7.0_55"
OpenJDK Runtime Environment (IcedTea 2.4.7) (7u55-2.4.7-1ubuntu1~0.13.10.1)
OpenJDK 64-Bit Server VM (build 24.51-b03, mixed mode)

The code is:

 if (args.length < 2) {
        System.out.println("SF   <retailername> retailername <manName> man");
        System.exit(1);
    }
    GetSoogrData wa = new GetSoogrData();
    try {
        BufferedReader bf = new BufferedReader(new FileReader(args[0]));

        String line = null;
        while ((line = bf.readLine()) != null) {
            Class c  = wa.getClass();


            c.getDeclaredMethod(line, null);
        }

The compiler gives warnings about a Raw Type (Class is a Raw Type) and also warnings on the getDeclaredMethod saying about Type. The class is just declared:

public class GetSoogrData {

    private HashMap<String, Integer> wordDictionary =   new HashMap<String, Integer>();
    private File inputFile;

    private File outputFile;
    private String retailerName;
    private String man;
    private String[] word;

    public void getTemperature() {
        System.out.println("device temp");
    }

I am testing with getTemperature.

I have tried a few versions of the code and there is no error but no result either. The code just seems to ignore the method completely. I tested without the getDeclaredMethod and it worked OK, so the method can be reached and the class instantiated. Hence the error lies with the actual getDeclaredMethod. I saw the Java version can affect this.

Has anyone any solution?

You should be doing something like:

Method method = c.getDeclaredMethod(line);
method.invoke(wa);//this will call method whatever is there in your line method without any parameters

First, The line:

c.getDeclaredMethod(line, null);

Should be:

c.getDeclaredMethod(line);

getDeclaredMethod receives a varargs array of Class objects, so your non-parameterized method should receive an empty array, not null .

Second, you should invoke the method object after getting it, using Method.invoke(Object) .

Anyway, debugging would probably be solving your problem. You could just run line by line to see if the code line is "ignored", then you could probably figure out what's wrong with your code...

我刚刚发现对我在getDeclaredMethod上的第二个查询的答案不起作用,NoSuchMethodException-解决方案包括添加String.class作为参数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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