java 从另一个类获取一个已经存在的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30852137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:45:19  来源:igfitidea点击:

Get an already existing object from another class

javaclassobject

提问by RagnarLodbrok

Im very new to programming and want to know if I can somehow get the object from a class where I already used new MyClass();to use it in another class and that I don't need to use new MyClass();again. Hope you get the point.

我对编程很陌生,想知道我是否可以从一个类中获取对象,我已经new MyClass();在另一个类中使用过它并且不需要new MyClass();再次使用它。希望你明白这一点。

Some very simple example:

一些非常简单的例子:

class MyFirstClass
{
    Something st = new Something();
}

class Something()
{
    // some code
}

class MySecondClass
{
    // This is where I want to use the object from class Something()
    // like
    getObjectFromClass()
}

采纳答案by Anatoly

You can use Singleton patternto achieve this

您可以使用单例模式来实现这一点

This is kickoff example of such object. It has a private constructorand public class methodgetInstance:

这是此类对象的启动示例。它有一个私有构造函数公共类方法getInstance

static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class

静态方法,在它们的声明中有静态修饰符,应该用类名调用,而不需要创建类的实例

When we make a call to getInstanceit checks if an object has been created already and will return an instance of already created objected, if it wasn't created it will create a new object and return it.

当我们调用getInstance它时,检查一个对象是否已经被创建并返回一个已经创建的对象的实例,如果它没有被创建,它将创建一个新对象并返回它。

public class SingletonObject {

private static int instantiationCounter = 0;    //we use this class variable to count how many times this object was instantiated

private static volatile SingletonObject instance;
private SingletonObject() { 
    instantiationCounter++;
}

public static SingletonObject getInstance() {
    if (instance == null ) {
       instance = new SingletonObject();
    }

    return instance;
}

public int getInstantiationCounter(){
    return instantiationCounter;
}
}

To check how does this work you can use the following code:

要检查这是如何工作的,您可以使用以下代码:

public static void main(String[] args)  {
        SingletonObject object = SingletonObject.getInstance();

        System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");

        object = SingletonObject.getInstance();

        System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");

        object = SingletonObject.getInstance();

        System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");

    }

回答by Ankur Anand

Since you have just started coding won't give you a term like reflection and all.. here is one of the simple way is have a public getter()method.

由于您刚刚开始编码,因此不会给您提供诸如反射之类的术语getter()

Consider this simple example

考虑这个简单的例子

class Something {

    private int a=10;

    public int getA() {
        return a;
    }


}

Here is the First which has a public method which return the object that i created in this class for the Something Class

这是第一个,它有一个公共方法,它返回我在这个类中为Something 类创建的对象

class MyFirstClass {

    private Something st;

    public MyFirstClass() {
        this.st = new Something();
    }

    public Something getSt() {
        return st;
    }




}

Accessing it from another Class

从另一个类访问它

class MySecondClass {

    public static void main(String...strings ){
        MyFirstClass my =new MyFirstClass();
        System.out.println(my.getSt().getA());
    }


}

Output: 10

输出: 10

If You wan't to verify

如果您不想验证

Inject this function in MyFirstClass

将这个函数注入 MyFirstClass

public void printHashcode(){
        System.out.println(st);
    }

and then print the hash codes from both methods in MySecondClass

然后打印两种方法的哈希码 MySecondClass

class MySecondClass {

类 MySecondClass {

public static void main(String...strings ){
    MyFirstClass my =new MyFirstClass();
    System.out.println(my.getSt());
    my.printHashcode();

}

}

}

You will see that indeed you are using the Object created in MyFirstClassin MySecondClass.

你会看到,事实上你正在使用中创建的对象MyFirstClassMySecondClass

Because this will give you same hashcode output.

因为这会给你相同的哈希码输出。

Output On my machine.

在我的机器上输出。

Something@2677622b
Something@2677622b

回答by John

Singleton pattern lets you have single instance which is 'globally' accessible by other classes. This pattern will 'guarantee' that you have only one instance in memory. There are exceptions to one instance benefit, such as when deserializaing from file unless care is taken and readResolveis implemented.

单例模式让您拥有可由其他类“全局”访问的单个实例。这种模式将“保证”您在内存中只有一个实例。一个实例的好处有例外,例如从文件反序列化时,除非小心并readResolve实施。

Note that class Something right now has no state(fields), only behavior so it is safe to share between multiple threads. If Something had state, you would need to provide some kind of synchronization mechanism in multi thread environment.

请注意,现在类Something没有状态(字段),只有行为,因此在多个线程之间共享是安全的。如果Something有状态,则需要在多线程环境中提供某种同步机制。

Given such stateless Singleton, it would be better to replace it with class that contains only static methods. That is, unless you are implementing pattern such as Strategy which requires interface implementation, then it would be good idea to cache instance like bellow with Singleton pattern.

鉴于这种无状态的单例,最好将其替换为仅包含静态方法的类。也就是说,除非您正在实现诸如需要接口实现的策略之类的模式,否则最好使用单例模式缓存如下所示的实例。

You should rework your Something class like this to achieve singleton:

你应该像这样重写你的Something类来实现单例:

public class Something {

    private static final Something INSTANCE = new Something ();

    private Something () {

        // exists to defeat instantiation
    }

    public Something getInstance() {
        return INSTANCE;
    }


    public void service() {
        //...
    }

    public void anotherService() {
        //..
    }
}

回答by jrahhali

Instead of using the Singleton pattern, a better pattern to use is dependency injection. Essentially, you instantiate the class you want to share, and pass it in the constructor of every class that needs it.

除了使用单例模式,更好的模式是依赖注入。本质上,您实例化要共享的类,并将其传递到每个需要它的类的构造函数中。

public class MainClass {
    public static void main(String[] args) {
        SharedClass sharedClass = new SharedClass();
        ClassA classA = new ClassA(sharedClass);
        ClassB classB = new ClassB(sharedClass);
    }
}

public class ClassA {
    private SharedClass sharedClass;

    public ClassA(SharedClass sharedClass) {
        this.sharedClass = sharedClass;
    }
}

public class ClassB {
    private SharedClass sharedClass;

    public ClassB(SharedClass sharedClass) {
        this.sharedClass = sharedClass;
    }
}

回答by Amin Abu-Taleb

If FirstClass and SecondClass are somehow related, you can extract that common object you're using to a super class, and that's the only scope in which you're planning to use this object.

如果 FirstClass 和 SecondClass 以某种方式相关,您可以将您正在使用的公共对象提取到超类,这是您计划使用此对象的唯一范围。

    public class SuperClass{
        Something st = new Something();

        public Something getObjectFromClass(){
           return st;
        }
    }

    public class MyFirstClass extends SuperClass{
       getObjectFromClass();
    }

    public class MySecondClass extends SuperClass{
       getObjectFromClass();
    }

Otherwise, if you plan to use that instance somewhere else you should use a Singleton object. The easiest way of doing this is:

否则,如果您打算在其他地方使用该实例,则应使用 Singleton 对象。最简单的方法是:

enum Singleton
{
    INSTANCE;

    private final Something obj;

    Singleton()
    {
        obj = new Something();
    }

    public Something getObject()
    {
        return obj;
    }
}

You use it:

你用吧:

Singleton.INSTANCE.getObject();

回答by thekruled

Okay firstly you can use inheritance e.g.

好的,首先你可以使用继承,例如

class MyFirstClass

{

Something st = new Something();

}

class Something()
{
// some code
}

class MySecondClass extends myFirstClass
{
// This is where I want to use the object from class Something()
// like
MySecondClass obj = new MySecondClass();
obj.method();  //Method from myfirstclass accessible from second class object

}

Or if you dont want any objects and just the method you can implement interfaces e.g.

或者,如果您不想要任何对象而只想要您可以实现接口的方法,例如

public interface MyFirstClass
{

//example method
 public abstract void saying();    //no body required

Something st = new Something();
}

class Something()
{
// some code
}

class MySecondClass implements MyFirstClass //Have to implement methods
{

   public void saying(){         //Method implemented from firstClass no obj
   System.out.println("Hello World");
 }
 getObjectFromClass()
}