简体   繁体   English

使用JavaBeans在类之间传递数据

[英]Use JavaBeans to pass data between classes

A Piece of important information: The classes are all separate files and there are about 10 beans in total . 一条重要信息:这些类都是单独的文件,总共有大约10个bean。

I am working on a project with multiple classes through which data must be passed. 我正在开发一个包含多个类的项目,通过这些类必须传递数据。 Ie a couple strings from say Class1 must be able to be used in Class2. 即Class1中的几个字符串必须能够在Class2中使用。

My program uses JavaBeans with set and get methods but if I set a bean in one class and try to get that data in another class I just get a null value returned. 我的程序使用带有set和get方法的JavaBeans但是如果我在一个类中设置一个bean并尝试在另一个类中获取该数据,我只返回一个null值。

I am unsure as to what the best method is, I have the beans nicely defined and would like to keep using them but I do not know how. 我不确定最好的方法是什么,我有很好的定义豆,并希望继续使用它们,但我不知道如何。

Could someone point me in the correct direction or give an example. 有人能指出我正确的方向还是举个例子。 Thanks 谢谢

Edit 编辑

Bean class snippet; Bean类片段;

public class beans implements java.io.Serializable {



private String string1;


public String getstring1() {

    return this.string1;
}

public void setstring1(String string1) {
    this.string1 = string1;
}

And the setter code in say class1: 并且setter代码在class1中:

beans bean = new beans();   
bean.setstring1("test");

And the class where the bet is "got", class2 并且下注的类别“得到”,class2

beans bean = new beans(); String text = bean.getstring1();

That is pretty much how I am using the beans and they are not working as I want them to. 这就是我如何使用bean而且它们不能按照我的要求工作。

In your example you are creating a new bean in each class. 在您的示例中,您将在每个类中创建一个新bean。 The first and the second class have references to two different objects, that's why they can't access the same values. 第一个和第二个类引用了两个不同的对象,这就是为什么它们不能访问相同的值。

There are multiple ways to solve this and it really depends on your application. 有多种方法可以解决这个问题,这取决于您的应用程序。 But let me suggest one generic solution. 但是,我建议一个通用的解决方案。

You can create a BeanRepository which is responsible for having references to all bean objects. 您可以创建一个BeanRepository ,它负责引用所有bean对象。 Other classes then need to know the id of the bean and they can get a reference. 然后其他类需要知道bean的id ,他们可以获得引用。

BeanRepository (notice the static methods): BeanRepository(注意静态方法):

public class BeanRepository {
    private static Map<Integer, Bean> beanMap = new HashMap<Integer, Bean>();

    public static void putBean(int id, Bean bean) {
        beanMap.put(id, bean);
    }

    public static Bean getBean(int id) {
        return beanMap.get(id);
    }
}

The bean: 豆子:

public class Bean {
    private String name;

    public Bean(String name) {
        this.name = name;
    }

    public String whoAmI() {
        return name;
    }
}

Classes A and B: A类和B类:

public class ClassA {
    private Bean bean;

    public ClassA(int beanId) {
        this.bean = BeanRepository.getBean(beanId);
    }

    public void test() {
        System.out.println("I am ClassA. You are " + bean.whoAmI());
    }
}

public class ClassB {
    private Bean bean;

    public ClassB(int beanId) {
        this.bean = BeanRepository.getBean(beanId);
    }

    public void test() {
        System.out.println("I am ClassB. You are " + bean.whoAmI());
    }
}

Test method: 测试方法:

public class Main {
    public static void main(String[] args) {
        BeanRepository.putBean(1, new Bean("one"));

        ClassA a = new ClassA(1);
        ClassB b = new ClassB(1);

        a.test();
        b.test();
    }
}

container I am very puzzled by your question. 容器我对你的问题很困惑。 Are you referring to Enterprise Java Beans? 您指的是Enterprise Java Bean吗?

If you just mean ordinary JavaBeans just featuring get and set methods, the first thing I would advise is to learn how to use jUnit . 如果你只是说普通的JavaBeans只是使用get和set方法,我建议的第一件事就是学习如何使用jUnit Test your data bean first inorder to ensure it is working as intended. 首先测试您的数据bean,以确保它按预期工作。

Beside that if your class live within the same JVA (you only start a single java.exe / run a single application) everything should just work fine. 除此之外,如果你的班级住在同一个JVA(你只启动一个java.exe /运行一个应用程序),一切都应该工作正常。

public class Data { 
    private String value; 
    public void set(String value) { this.value = value; }
    public String get() { return this.value; }
}

public class ClassA {
    Data data = new Data();
    ClassA() { data.set("From ClassA"); }
}

public class ClassB {
    Data data;
    ClassB(Data data) { this.data = data; }
    public void print() {
      System.out.println(data.get());
    }
}

public static void main(String args []) {
    new ClassB(new ClassA().data).println();
}

This is a simple example using a data object to pass informations around. 这是一个使用数据对象传递信息的简单示例。

Hope this is what you want to know. 希望这是你想知道的。

[Update] [更新]

After you add some code I see the problem. 添加一些代码后,我看到了问题。 As other users already wrote you are creating new objects (instances) every time. 正如其他用户已经写过的那样,您每次都在创建新对象(实例)。 Since the string1 is a property of that class ever instance of it will have their own value. 由于string1是该类的属性,因此它的实例将具有自己的值。

The default example is a person. 默认示例是一个人。 Creating a Person class with a property name (similar to your string1) you can create two persons (instances of class Person). 创建一个具有属性名称的Person类(类似于您的string1),您可以创建两个人(Person类的实例)。 You can now name every person individual. 您现在可以为每个人命名。

Thats what Class mean. 这是什么类意味着什么。 You specify the properties (instance variables) and behavior (methods) of instances (actual object) of that class. 您可以指定该类的实例(实际对象)的属性(实例变量)和行为(方法)。

If you want to share information you need a way to pass(!) an instance (object) of a Class to other instances. 如果要共享信息,则需要一种方法将(!)类的实例(对象)传递给其他实例。 In Java different way exist. 在Java中存在不同的方式。 You can use static variables which are global (bound to the Class instead of an instance of a class), you can use singleton pattern (which employes the static variable), you can use ThreadLocal (a global store limited to the current thread), you may use managers / repositories storing objects and you pass the manager / repository objects along, you can use databases or you can use a dependency injector which is like a transparent object manager. 你可以使用全局的静态变量(绑定到Class而不是类的实例),你可以使用singleton模式(它使用静态变量),你可以使用ThreadLocal(一个局限于当前线程的全局存储),您可以使用存储对象的管理器/存储库并传递管理器/存储库对象,您可以使用数据库,也可以使用依赖注入器,它类似于透明对象管理器。 Those are basically it. 基本上就是这样。

For your use case I would use Singleton first. 对于您的用例,我将首先使用Singleton。

public class MySingleton {
   private static Bean myBean;
   public static void setBean(Bean myBean) { MySingleton.myBean = myBean; }
   public static Bean getBean() { return myBean; }
}

Using the class is straight forward: 使用该课程是直截了当的:

Bean bean = new Bean();
bean.setString1("test");
MySingleton.setBean(bean);
Bean bean2 = MySingleton.getBean();
System.out.println(bean2.getString1()); //prints test

But beware this is the lazy way of doing things. 但要注意这是懒惰的做事方式。 Using static has some draw backs if you have a complex project especially when it comes to serialization, concurrency and reuse. 如果你有一个复杂的项目,特别是在序列化,并发和重用方面,使用static会有一些缺点。

If you'se serializing/deserializing your classes, make sure that 如果你序列化/反序列化你的类,请确保

  1. string fields themselves are not marked as transient. 字符串字段本身未标记为瞬态。

  2. you're not using custom writeObject(ObjectOutputStream ) methods in your object where you forgot your string fields. 您没有在您忘记字符串字段的对象中使用自定义writeObject(ObjectOutputStream)方法。

  3. you're not cloning your class with custom clone() methods where you forgot your string field 您没有使用自定义clone()方法克隆您的类,而您忘记了字符串字段

  4. you wrote setter and getter properly in the first place. 你首先正确地写了setter和getter。

and things shoud work ;) 和事情应该工作;)

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

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