简体   繁体   English

在Java中引用类对象

[英]Referencing a class object in java

Lets say I have a class User: 可以说我有一个班级用户:

public class User {
    String userID;
    String password;
    Integer connectID;
    String name;

    public User(String Name, String ID, String Pass, Integer connect) {
        userID = ID;
        password = Pass;
        connectID = connect;
        name = Name;
    }

    public String getUserID() {
        return userID;
    }

    public String getPassword() {
        return password;
    }

    public Integer getConnectID() {
        return connectID;
    }

    public String getName() {
        return name;
    }
}

And I have a section of my code which takes the connectID of a certain object and puts it into a varaible connectionID = (accounts.get(i)).getConnectID(); 而且我的代码中有一部分采用了某个对象的connectID并将其放入可变的connectionID = (accounts.get(i)).getConnectID(); where accounts is an ArrayList holding all of the objects created. 其中accounts是一个ArrayList,其中包含所有创建的对象。 Would there be a way for me to use the connectionID variable to relate back to the object again in another method textWindow.append("localhost." + ... + getDateTime() + " > "); 我是否有办法在另一个方法textWindow.append("localhost." + ... + getDateTime() + " > ");使用connectionID变量再次与该对象相关联textWindow.append("localhost." + ... + getDateTime() + " > "); where the ... part is the part that I want to use the getConnectID() method on. ...部分是我要在其上使用getConnectID()方法的部分。

Don't store connectionID as a variable. 不要将connectionID存储为变量。 It is already stored within the User object. 它已经存储在User对象中。 Instead, store the User as a variable so it's contents can be accessed again later: 而是将User存储为变量,以便稍后可以再次访问其内容:

//Before the for loop, in a wider scope, declare the User:
User user;
//Then, in the for loop, initialize it:
user = accounts.get(i);
//As it was declared outside the for loop, it can be accessed later:
textWindow.append("localhost." + "User ID: " + user.getConnectionID() + " at " + getDateTime() + " > ");//or however you wish to format it

One possible solution here is to change the type of connectionID from Integer to a class you create 一种可能的解决方案是将connectionID的类型从Integer更改为您创建的类

class ConnectionID {

    private final Integer id;
    private final User user;

    ConnectionID(final Integer id,
                 final User user) {
        this.id = id;
        this.user = user;
    }

    public getUser() {
        return this.user;
    }

}

Now you can relate back to the user, given a connection id. 现在,您可以在指定连接ID的情况下与用户建立联系。

Assuming that connectID is unique to each User . 假设connectID对每个User唯一。 You could loop through the accounts and compare the connectID . 您可以遍历accounts并比较connectID

public User getUser(int connectID){
    for (User user : accounts){
        if (user.getConnectID()==connectID){
            return user;
        }
    }
    return null;
}

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

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