简体   繁体   English

是否可以从另一个类访问非静态类的实例

[英]is it possible to access an instance of a non static class from another class

lets say I have classA and classB. 可以说我有classA和classB。

I know that I cannot just call a non static variable or method of classA from classB because the system doesn't know which instance of classA I want to use. 我知道我不能只从classB调用非静态变量或classA的方法,因为系统不知道我要使用哪个classA实例。 but is there a way to specify which instance? 但是有办法指定哪个实例吗?

something like this: in class AI declare a static variable which whould hold the some sort of ID or context to the specific instance of the class 像这样:在类AI中声明一个静态变量,该变量应持有该类特定实例的某种ID或上下文。

class classA{
  static Instance instance 

  onCreate(){
    instance = thisInstance();
  }

  Method1(){
   }
}

then in class BI would refer to that instance like this: 然后在类BI中将这样引用该实例:

  ClassA.instance.method1();

is something like this possible? 这样可能吗? if so, what is the exact syntax? 如果是这样,确切的语法是什么?

[Bonus]: if no, what is the simplest way invoke a method in a class from another class? [奖励]:如果没有,从另一个类中调用一个类中的方法的最简单方法是什么? I assume some sort of event handling would be required. 我假设需要某种事件处理。 (I come from the embedded c world) (我来自嵌入式c世界)

Declare a static member in ClassA 在ClassA中声明一个静态成员

public class ClassA {
    public static ClassA object = new ClassA();

    public void doStuff() {
        // do stuff
    }
}

Then in ClassB 然后在ClassB中

public void someMethod() {
     ClassA.object.doStuff();
}

In class B, you can define: 在B类中,您可以定义:

Class B {
  private static ClassA instanceA = null; // By making it null, you can later confirm that the instance was successfully passed by making sure instanceA != null.

  /**
  * This method allows you to pass the instance of ClassA into B so you can use its non-static methods.
  */
  public static void setInstanceA(ClassA instance) {
    instanceA = instance;
  }
}

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

相关问题 可以从在A类实例中创建的另一个B类实例访问A类实例的字段 - is possible to access to the field of a A class instance from another B class instance created in the A class instance 如何使用一个类中的静态变量来更新另一个类中的非静态实例变量? - How to use a static variable from a class to update a non-static instance variable in another class? 非静态嵌套线程-来自另一个类的访问(Java) - Non-static nested thread - access from another class (Java) 从另一个类访问非静态变量 - access non-static variable from another class 我们无法从静态方法访问非静态实例,但可以启动类。 怎么样? - We cant access non static instance from a static method, but can initiate a class. how? 从另一个类调用非静态方法 - Call non static methods from another class 从另一个类调用非静态void - Call a non static void from another class 匿名线程类无法访问非静态实例变量 - Anonymous thread class not able to access non static instance variables 是否可以从内部类实例访问外部类实例? - Is it possible to access an outter class instance from an inner class instance? 如何创建实例变量以从另一个 class 调用非静态方法? - How do you create an instance variable to call a non-static method from another class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM