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,518
  • 20
  • 73
  • 112

3 Answers3

2

Import :

import java.net.URL;

Use the class literal:

URL url = NLPApplications.class.getResource("big.txt");
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
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
  • 40,646
  • 13
  • 77
  • 103
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
  • 28,160
  • 11
  • 74
  • 110