简体   繁体   English

如何从另一个类的静态类中调用方法?

[英]How to call a method from a static class in another class?

I have a method "b(Class g)" in a static class "a" 我在静态类“ a”中有一个方法“ b(Class g)”

so myclass.java contains... 所以myclass.java包含...

public static class a{

     public void b(Class g){
     ....
     }

}

than another method in the same myclass.java 比同一个myclass.java中的另一个方法

public void c(){

if(...){}
else{
   b();  //i want to call b but i get an error asking me to create the method

}

Your method b needs an argument of type Class that's why it is complaining. 您的方法b需要一个Class类型的参数,这就是它抱怨的原因。

Update 更新

You also have a strange class declaration public static class a 您也有一个奇怪的类声明public static class a

As per Java specification on Class declaration Not all modifiers are applicable to all kinds of class declarations...... The access modifier static pertains only to member classes which means you have wrong static modifier in your public class declaration. 根据Java关于类声明的规范,并非所有修饰符都适用于所有种类的类声明…… The access modifier static pertains only to member classes ,这意味着您在公共类声明中使用了错误的static修饰符。

Change you top level class declaration to public class a first and then see how it behaves. 首先将您的顶级类声明更改为public class a ,然后查看其行为。

There are two things to note: 1) Even though the inner class 'a' is declared static, the method b(Class g) is not static. 有两点需要注意:1)即使内部类'a'被声明为静态的,方法b(Class g)也不是静态的。 So in order to access the b(Class g) method of class 'a', you still need to create an instance of 'a' ie 因此,为了访问类“ a”的b(Class g)方法,您仍然需要创建“ a”的实例,即

a a1 = new a();
a1.b(SomeClass.class);

Important: Declaring a class static doesn't make the methods of that class static. 重要提示:声明一个类为静态并不会使该类的方法成为静态。

2) When invoking the method b(Class g) , you need to pass the Class argument. 2)调用方法b(Class g) ,您需要传递Class参数。 Calling b(); 调用b(); with no argument will result in error. 没有参数将导致错误。

If you want to call b(Class g) without creating an instance of class 'a', then mark the method b(Class g) to be static. 如果要在不创建类'a'的实例的情况下调用b(Class g) ,则将方法b(Class g)标记为静态。 ie

public static class a{

     static public void b(Class g){
     ....
     }

}

To get a better understanding of static nested class, read this 为了更好地了解静态嵌套类,请阅读此内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM