Error reason: A public String getcontent () method and a main () method are written in a class, and the GetContent () method contains the GetClass () method, which is called directly in the main () method GetContent () There is a mistake of the title. The workaround: Instantiate the class first and then call GetContent () there's no problem.
GetProperties GP = new GetProperties ();
String s = gp.getcotent ();
So no more static. Note: Non-static members (including methods and variables) cannot be accessed directly in a static method.
because, a non-static variable is dependent on the existence of an object, and the object must be instantiated before its variables exist in memory. For example, a class Student represents a student, and it has a variable string address. If the class is not instantiated, then its address variable does not exist. Non-static methods require access to non-static variables, so access to non-static methods is also done for a specific object. Access to it is generally carried out by means of objectname.methodname (args ...). Static members, which are not dependent on the existence of an object, can be accessed even if the object to which the class belongs does not exist, and it is global to the entire process. Therefore, non-static members cannot be accessed directly from within a static method. The code is as follows:
Import java.io.FileNotFoundException;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.util.Properties;
public class GetProperties {//without a static public
string Getcotent () {//without a static
string content= "";
try {
Properties Properties = new properties ();
InputStream is = GetClass (). getResourceAsStream ("Test.properties"),//ok
//inputstream is = GetClass (). getClassLoader (). getResourceAsStream ("test.properties"); Error:exception in thread "main" Java.lang.NullPointerException
properties.load (IS);
Is.close ();
Content = Properties.getproperty ("Str1″);
} catch (FileNotFoundException ex) {
ex.printstacktrace ();
} catch (IOException ex) {
ex.printstacktrace ();
}
return content;
}
public static void Main (string[] args) {
GetProperties GP = new GetProperties ();//Instantiate
String s = gp.getcotent ();
System.out.println (s);
}
The contents of Test.properties are str1=123