繁体   English   中英

Java 类如何从条目 class 中获取信息?

[英]How do Java classes get information from the Entry class?

So lets say that in my entry point class (ie the class which runs when the program starts (which has the public static void main(String args[]) function). In that class I have this variable:

private ArrayList<String> myData=new ArrayList<String>();

这个 class 实例化了另一个 class,它需要访问入口点 class 的myData成员。 它如何检索这个 arraylist?

编辑:为了澄清,在main()方法中我可以这样做:

SomeOtherClass myClass=new SomeOtherClass();

然后我可以这样做:

myClass.someMethod();

但是,在myClass object 中,我如何从条目 class 中执行方法/检索某些内容,该条目实例化了myClass object?

让 class 实例化访问myData的最佳方法是在创建时将其传递给构造函数。

然后,在您的构造函数中,您可以将 ArrayList 保存到ArrayList的成员变量中。

例如,您的 object 构造函数将如下所示:

private ArrayList<String> myData;

public YourObjConstructor(ArrayList<String> data){
    myData = data;
}

听起来你的入口点仍然是 static 当它调用其他一些 class 时,但你的 ArrayList 是它的一个实例的成员。 您需要离开 static 世界并进入实例。

我会将您的 main 方法重构为私有构造函数,并放入一个新的 main() 将其作为新实例启动。

请注意,此代码非常粗略,但它应该有助于说明您需要做什么。

public class EntryPoint {
    private ArrayList<String> myData=new ArrayList<String>();

    public static void main( String[] args ) {
        EntryPoint ep = new EntryPoint();
        ep.init();
    }

    private void init() {
        // Populate myData perhaps?

        SomeOtherClass myClass=new SomeOtherClass();
        myClass.someMethod( this );
    }

    public List<String> getMyData() {
        return myData;
    }
}   

public class SomeOtherClass {
    public void someMethod( EntryPoint entry ) {
        List<String> data = entry.getMyData();
        // do stuff with data..!
    }
}

包含main()的 class 只是一个普通的 class。 在您的情况下,您必须public myData并且可能公开static (或者,当然,添加访问器)。 就像您对任何其他 class 所做的那样。

您还可以将Entry object 传递给另一个 class,如下所示:

public static void main(String[] args) {
    Entry entry = new Entry();
    SomeOtherClass myClass=new SomeOtherClass(entry);
    // continue as before
}

暂无
暂无

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

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