java:不能从静态上下文错误中引用非静态变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/926822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java : non-static variable cannot be referenced from a static context Error
提问by phill
The following code is generating an error on the variable con2
saying "non-static variable con2 cannot be referenced from a static context Error."
I Googled for a resolution and they are suggesting the variable isn't initalized yet to make the methods available. Am I initializing this incorrectly? I also tried changing things to public but that didn't help either.
下面的代码在变量上产生了一个错误,con2
说 "non-static variable con2 cannot be referenced from a static context Error."
我在谷歌上搜索了一个解决方案,他们建议变量尚未初始化以使方法可用。我是否错误地初始化了这个?我也尝试将事情更改为公开,但这也无济于事。
import java.io.*;
import java.net.*;
import java.sql.*;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import net.sourceforge.jtds.jdbcx.JtdsDataSource;
import net.sourceforge.jtds.jdbc.Driver;
class testconnect {
private java.sql.Connection con2 = null;
private final String url2 = "jdbc:jtds:sqlserver://";
private final String serverName= "SQL01";
private final String portNumber = "2677";
private final String databaseName= "App";
private final String userName = "bob";
private final String password = "boob";
private final String selectMethod = "cursor";
private String getConnectionUrl2(){
System.out.println("initalizing jtds");
//String returnVal = url+serverName+":"+portNumber+";databaseName="+databaseName+";user="+userName+";password="+password+";instance="+instance+";";
String returnVal = url2+serverName+":"+portNumber+"/"+databaseName+";user="+userName+";password="+password;
System.out.println("url2: " + returnVal);
return returnVal;
}
public static void main (String[] args) {
con2 = java.sql.DriverManager.getConnection(getConnectionUrl2());
}
} //end class
采纳答案by waxwing
No, actually, you must declare your con2 field static:
不,实际上,您必须将 con2 字段声明为静态:
private static java.sql.Connection con2 = null;
Edit: Correction, that won't be enough actually, you will get the same problem because your getConnection2Url method is also not static. A better solution may be to instead do the following change:
编辑:更正,实际上这还不够,您会遇到同样的问题,因为您的 getConnection2Url 方法也不是静态的。更好的解决方案可能是进行以下更改:
public static void main (String[] args) {
new testconnect().run();
}
public void run() {
con2 = java.sql.DriverManager.getConnection(getConnectionUrl2());
}
回答by Clint Miller
Your main() method is static, but it is referencing two non-static members: con2 and getConnectionUrl2(). You need to do one of three things:
您的 main() 方法是静态的,但它引用了两个非静态成员:con2 和 getConnectionUrl2()。您需要做以下三件事之一:
1) Make con2 and getConnectionUrl2() static.
1) 将 con2 和 getConnectionUrl2() 设为静态。
2) Inside main(), create an instance of class testconnect and access con2 and getConnectionUrl2() off of that.
2) 在 main() 中,创建类 testconnect 的实例并访问 con2 和 getConnectionUrl2() 关闭它。
3) Break out a different class to hold con2 and getConnectionUrl2() so that testconnect only has main in it. It will still need to instantiate the different class and call the methods off that.
3) 分出一个不同的类来保存 con2 和 getConnectionUrl2() 以便 testconnect 中只有 main 。它仍然需要实例化不同的类并调用它的方法。
Option #3 is the best option. #1 is the worst.
选项#3 是最好的选择。#1 是最糟糕的。
But, you cannot access non-static members from within a static method.
但是,您不能从静态方法中访问非静态成员。
回答by Hymanr
You probably want to add "static" to the declaration of con2.
您可能想在 con2 的声明中添加“静态”。
In Java, things (both variables and methods) can be properties of the class (which means they're shared by all objects of that type), or they can be properties of the object (a different one in each object of the same class). The keyword "static" is used to indicate that something is a property of the class.
在 Java 中,事物(变量和方法)可以是类的属性(这意味着它们被该类型的所有对象共享),也可以是对象的属性(同一类的每个对象中的不同属性) )。关键字“static”用于表示某物是类的属性。
"Static" stuff exists all the time. The other stuff only exists after you've created an object, and even then each individual object has its own copy of the thing. And the flip side of this is key in this case: static stuff can't access non-static stuff, because it doesn't know which object to look in. If you pass it an object reference, it can do stuff like "thingie.con2", but simply saying "con2" is not allowed, because you haven't said which object's con2 is meant.
“静态”的东西一直存在。其他东西只有在你创建了一个对象之后才存在,即使这样,每个单独的对象都有它自己的副本。在这种情况下,另一方面是关键:静态的东西不能访问非静态的东西,因为它不知道要查看哪个对象。如果你向它传递一个对象引用,它可以做像“thingie .con2”,但不允许简单地说“con2”,因为您还没有说明哪个对象的 con2 是指。
回答by Ron
The simplest change would be something like this:
最简单的变化是这样的:
public static void main (String[] args) throws Exception {
testconnect obj = new testconnect();
obj.con2 = DriverManager.getConnection(obj.getConnectionUrl2());
obj.con2.close();
}
回答by Khangharoth
Java has two kind of Variables
Java有两种变量
a)
Class Level (Static) :
They are one per Class.Say you have Student Class and defined nameas static variable.Now no matter how many student object you create all will have same name.
Object Level :
They belong to per Object.If name is non-static ,then all student can have different name.
a)
班级(静态):
每个班级一个。假设您有学生班级并将名称定义为静态变量。现在无论您创建多少个学生对象,都将具有相同的名称。
对象级别:
它们属于每个对象。如果名称是非静态的,则所有学生都可以有不同的名称。
b)
Class Level :
This variables are initialized on Class load.So even if no student object is created you can still access and use static name variable.
Object Level:
They will get initialized when you create a new object ,say by new();
b)
类级别:
此变量在类加载时初始化。因此即使没有创建学生对象,您仍然可以访问和使用静态名称变量。
对象级别:当你创建一个新对象时,它们会被初始化,比如 new();
C)
Your Problem :
Your class is Just loaded in JVM and you have called its main (static) method : Legally allowed.
Now from that you want to call an Object varibale : Where is the object ??
C)
您的问题:您的类刚刚加载到 JVM 中,并且您调用了它的主要(静态)方法:合法允许。
现在你想调用一个对象变量:对象在哪里??
You have to create a Object and then only you can access Object level varibales.
您必须创建一个对象,然后只有您才能访问对象级别的变量。
回答by JavaUSer
This is an interesting question, i just want to give another angle by adding a little more info.You can understand why an exception is thrown if you see how static methods operate. These methods can manipulate either static data, local data or data that is sent to it as a parameter.why? because static method can be accessed by any object, from anywhere. So, there can be security issues posed or there can be leaks of information if it can use instance variables.Hence the compiler has to throw such a case out of consideration.
这是一个有趣的问题,我只是想通过添加更多信息来提供另一个角度。如果您了解静态方法的运行方式,您就可以理解为什么会抛出异常。这些方法可以操作静态数据、本地数据或作为参数发送给它的数据。为什么?因为静态方法可以被任何对象从任何地方访问。因此,如果它可以使用实例变量,则可能存在安全问题或者可能存在信息泄漏。因此编译器必须将这种情况排除在外。