Solution for :Cannot make a static reference to the non-static method

    最近在学习java,作为java的菜鸟和以前C语言思维带来的影响,在弄java时经常犯一些比较低级的错误,弄清楚这些低级的错误对于理解java有很好的帮助。所以记录一下。
Cannot make a static reference to the non-static method 这个错误估计是最常见的,当时还觉得奇怪为什么是这样的情况呢。
比如我写了下面 一段java的测试小程序来检验一个字符串是否是数字:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestStrIsNum {
	   public  boolean isNumeric(String str){ 
		   Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+"); 
		   Matcher isNum = pattern.matcher(str);
		   if( !isNum.matches() ){
		       return false; 
		   } 
		   return true; 
		}

	   public static void main(String[] argv)
		{
                    String a =new String("-1000");
		    
                    //if (isNumeric(a)) error:Cannot make a static reference to the non-static method
                    TestStrIsNum test = new TestStrIsNum();    
                    if (test.isNumeric(a))  
                        System.out.println("a = -1000 is a number");	    
		} 
}
Analysis and soultion:
You can't make a static reference to the non-static method, so you can change the un-static method to a static method or you need to create an object using new operator and call the method by object.method().

stackoverflow上explaination:
http://stackoverflow.com/questions/23860661/cannot-make-a-static-reference-to-the-non-static-method

你可能感兴趣的:(java)