[英]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.