从android中的静态方法调用非静态方法 [英] call non static method from static method in android
问题描述
我尝试从静态方法调用非静态方法但没有任何结果,我的应用程序崩溃
我的代码:
I tried to call non static method from static method but without any result ,my application works crash my code :
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAuth();
///
///
}
public static void setAuth() {
new MainActivity().d();
}
public void d()
{
Toast.makeText(getApplicationContext(), "fff",Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
是否允许从android中的静态方法调用非静态方法?
和如何???
Is it permissible to call non static method from static method in android?? and how???
推荐答案
类中的静态方法必须能够在不引用任何引用的情况下执行类的实例化:
A static method in a class must be able to be executed without any reference to an instantiation of the class:
class MyClass {
int information;
static int usefulNumber = 72;
int method() {
return information;
}
static int methodStatic() {
// Cannot refer to information
// But can refer to usefulNumber
}
}
因此,根据定义,它不能在类中执行非静态方法,因为该方法不存在,除非像@RhinoFeeder所说,你实例化了类并且将该实例化传递给静态类:
By definition therefore, it cannot execute a non-static method in the class because that method doesn't exist unless, as @RhinoFeeder says, you have instantiated the class and passed that instantiation to the static class:
static int methodStatic2(MyClass myClass) {
return myClass.method();
}
这篇关于从android中的静态方法调用非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!