不能从静态上下文中引用非静态方法
我想一劳永逸地理解这一点。
请原谅下面粘贴的大量代码,但我不想遗漏任何细节。
我唯一改变的是加载的 URL。但这并没有导致错误。
我想将我的函数称为“readPosiitons”。简单的解决方案,使其静态。真正的解决方案,我不确定。
请帮助我更好地了解如何以正确的方式解决此错误。
谢谢!!
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package PandL;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Scanner;
import toolBox.Secretary;
import toolBox.Secretary.positionObj;
/**
*
* @author Jason
*
*/
public class GarageComm {
public static void main(String[] args) throws MalformedURLException, IOException{
String retStr;
String startM;
String endM;
String myURL;
String[] Split1=null;
Integer lnCount;
HashMap hashPos=new HashMap();
hashPos= readPositions("holdingsBU.txt");//the error is here
myURL="http://myUrl?s=";
URL url = new URL(myURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
in.close();
}
public HashMap readPositions(String destFile){
HashMap<String, Secretary.positionObj> hashPositions=new HashMap<String,positionObj>();
Secretary mySecretary=new Secretary();
try{
File F=new File(destFile);
if(F.exists()){
System.out.println("File Exists: "+F.exists());
System.out.println(destFile);
Scanner sC= new Scanner(F);
while (sC.hasNext()){
String[] Splitter1;
Secretary.positionObj position=mySecretary.new positionObj();
Splitter1=sC.nextLine().split(",");
position.positionDate=Double.parseDouble(Splitter1[0]);
position.positionTicker=(Splitter1[1]);
position.positionOpen=Double.parseDouble(Splitter1[2]);
position.positionPrice=Double.parseDouble(Splitter1[3]);
position.positionSMA=Double.parseDouble(Splitter1[4]);
position.positionUpdated=Double.parseDouble(Splitter1[5]);
position.priceUpdated=Double.parseDouble(Splitter1[6]);
position.updateDate=Double.parseDouble(Splitter1[7]);
hashPositions.put(position.positionTicker.trim(), position);
}
}else{
System.out.println("File Created: "+ F.createNewFile());
System.out.println("----No previous positions----");
}
}catch (Exception E){
System.err.println(destFile + " does not exist.");
hashPositions.put("ERROR", null);
E.printStackTrace();
}
return hashPositions;
}
}
I would like to understand this once and for all.
With this please excuse the mass of code pasted below, but I do not want to leave out any details.
The only thing I changed is the URL loaded. But this is not causing the error.
I would like to call my function "readPosiitons". Easy solution, make it static. Real solution, I am not sure of.
Please help me to better understand how to solve this error in the correct way.
Thanks!!
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package PandL;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Scanner;
import toolBox.Secretary;
import toolBox.Secretary.positionObj;
/**
*
* @author Jason
*
*/
public class GarageComm {
public static void main(String[] args) throws MalformedURLException, IOException{
String retStr;
String startM;
String endM;
String myURL;
String[] Split1=null;
Integer lnCount;
HashMap hashPos=new HashMap();
hashPos= readPositions("holdingsBU.txt");//the error is here
myURL="http://myUrl?s=";
URL url = new URL(myURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
in.close();
}
public HashMap readPositions(String destFile){
HashMap<String, Secretary.positionObj> hashPositions=new HashMap<String,positionObj>();
Secretary mySecretary=new Secretary();
try{
File F=new File(destFile);
if(F.exists()){
System.out.println("File Exists: "+F.exists());
System.out.println(destFile);
Scanner sC= new Scanner(F);
while (sC.hasNext()){
String[] Splitter1;
Secretary.positionObj position=mySecretary.new positionObj();
Splitter1=sC.nextLine().split(",");
position.positionDate=Double.parseDouble(Splitter1[0]);
position.positionTicker=(Splitter1[1]);
position.positionOpen=Double.parseDouble(Splitter1[2]);
position.positionPrice=Double.parseDouble(Splitter1[3]);
position.positionSMA=Double.parseDouble(Splitter1[4]);
position.positionUpdated=Double.parseDouble(Splitter1[5]);
position.priceUpdated=Double.parseDouble(Splitter1[6]);
position.updateDate=Double.parseDouble(Splitter1[7]);
hashPositions.put(position.positionTicker.trim(), position);
}
}else{
System.out.println("File Created: "+ F.createNewFile());
System.out.println("----No previous positions----");
}
}catch (Exception E){
System.err.println(destFile + " does not exist.");
hashPositions.put("ERROR", null);
E.printStackTrace();
}
return hashPositions;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
真正的解决方案?不要在
main()
方法中放入太多内容。那是给菜鸟的。Java 是一种面向对象的语言。将逻辑放入与 GarageComm 类关联的方法中。
main()
应该做的只是实例化一个实例并调用它的方法。像这样改变它:
Real solution? Don't put so much stuff in the
main()
method. That's for noobs.Java's an object-oriented language. Put the logic inside methods associated with the
GarageComm
class.main()
should do little more than instantiate an instance and call its methods.Change it like this:
对于新的 Java 程序员来说,这是典型的思维混乱。
static
方法不属于对象。非静态
方法属于一个对象。您使用
main
方法约定来启动程序,并且要求该方法必须是静态的。从
静态
方法转换为非静态
方法的技巧是,您必须创建一个对象,以便可以调用该对象的方法。即new GarageComm().readPositions(...)
。我只是认为你不必在这里,所以将 readPositions 标记为静态也会更简单。This is a typical mindbender for new Java programmers.
A
static
method does not belong to an object. A non-static
method belongs to an object.You use the
main
-method convention to have your program started, and it is required that that method must be static.The trick to get from a
static
method to a non-static
method, is that you must create an object so you can call the method on that. I.e.new GarageComm().readPositions(...)
. I just don't think you have to here, so it would be simpler to just mark readPositions as static too.您需要使函数静态:
创建 GarageComm 实例也可以,但在 Java 中这是不好的编程习惯,因为该对象没有状态。
You need to make your function static:
Creating an instance of GarageComm would work too, but this is bad programming practice in Java, since that object has no state.
如果方法不是静态的,则必须在对象“上”调用它。当从非静态方法调用方法时,该对象是隐含的——它是第一个方法被调用的对象。但是,当从静态方法调用它时,没有隐含的对象,因此要调用该方法,您必须提供一个对象:
由于
GarageComm
没有自己的状态,因此没有理由创建 < code>GarageComm 对象,因此最好将该方法标记为静态,这样就不需要任何对象来调用它。If a method is not static, then it must be called "on" an object. When calling a method from a non-static method, that object is implied -- it's the object the first method was called on. But when calling it from a static method, there is no implied object, so to call the method, you must supply an object:
Since
GarageComm
has no state of its own, there's no reason to create aGarageComm
object, so it's just as well you mark the method static, so no object is required to call it.在这种情况下,最好将该方法设为静态。另一种方法就是用它
来代替。
那么,为什么会出现这个错误?
静态方法不能调用同一个类中的非静态方法。听起来很奇怪,但这是有原因的。考虑一下:
非静态方法可能取决于对象的状态,即实例变量。
静态方法可以从外部调用,无需实例化
现在,如果我们允许静态方法与非静态方法(和非静态变量)一起使用,他们可能会失败。所以,这是一种预防。
我什么时候应该考虑将方法设为静态?
现在,为什么不将方法设为
静态
?,很好,你应该做一个如果方法的功能不依赖于对象的状态,则方法为静态。
如果它只使用传递的参数和一些静态内容(静态变量、静态方法)并返回(有/没有结果、抛出异常),请考虑将其设为静态方法。
更新:看起来这篇文章让一些人感到困惑,所以更新了答案。
It's a good idea in this case to make the method static. The other way is to use
instead.
So, why this error?
A static method can not call a non-static method in the same class. It sounds bizarre, but there is a reason for it. Consider this:
Non static methods may depend on the state of the objects, the instance variable to say.
Static methods can be called from out-side without instanciating
Now, if we allow static methods to play with non-static method (and non static variables), they might fail. So, it is a kind of prevention.
When should I consider making a method static?
Now, come to, why not make the method
static
?,Very well, you should make a method static if it's functionality does not depend on the object's state.
If it just uses the passed parameters and some static stuffs (static variable, static methods) and returns (with/without a result, throwing exception anything), consider making it static method.
update: looked like this post confused a couple of people so updated the answer.