2

I have a class SpellingSuggestor, whose constructor has the signature


public SpellingSuggestor(File file) throws IOException { // something }

I want to invoke its constructor from another class. The code goes something like this

public class NLPApplications
    public static void main(String[] args) {    
        String w= "randomword";
        URL url = getClass().getResource("big.txt");
        File file = new File(url.getPath());

        System.out.println((new SpellingSuggestor(file)).correct(w));   
    }
}

But the above shows error in the URL url.. line saying

  1. URL cannot be resolved to a type.
  2. cannot make a static reference to the non-static method getClass() from the type Object.

What is going wrong ?


I looked at this question How to pass a text file as a argument?. I am not comfortable with handling files in Java and so this question.

Community
  • 1
  • 1
OneMoreError
  • 7,132
  • 17
  • 67
  • 108

3 Answers3

2

Import :

import java.net.URL;

Use the class literal:

URL url = NLPApplications.class.getResource("big.txt");
AllTooSir
  • 47,910
  • 16
  • 124
  • 159
2

getclass() is a non-static method and you can not make reference from static main method.

why it is so? find here it is already answered by danben

And work around is -

NLPApplications.class.getClass().getResource("big.txt");
Community
  • 1
  • 1
Subhrajyoti Majumder
  • 39,719
  • 12
  • 74
  • 101
2

because you are trying to access a non-static method in static Main method which is not allowed, you have to use TheClassName.class instead of getClass().

Zaheer Ahmed
  • 27,470
  • 11
  • 72
  • 109