在Java 8中,可以选择从类中持续返回toString方法。

huangapple go评论74阅读模式
英文:

Optional in java 8 keep returning toString method from class

问题

我对Java 8中的`java.util.Optional.ofNullable`库有一个问题
我已经编写了以下代码但我希望它将返回类字段的值但我始终得到类的`toString`方法可能导致这种行为的原因是什么呢

    import static java.util.Optional.ofNullable;
    
    public class Main12 {
    
        public static String getName(User user){
            return ofNullable(user).map(User::getName).orElse("noFound");
        }
    
        public static void main(String[] args) {
            User user = new User();
            user.setName("ew");
            System.out.println(user);
        }
    
    }

我从终端获得的结果是`User{id=null, name='ew', age=0, roles=[]}`。我希望我能从User类中获得name字段的值

    public class User {
        private Long id;
        private String name;
        private int age;
        private Set<Role> roles = new HashSet<>();
    
        public User(long id, String name, int age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }
        public User(){
    
        }
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public Set<Role> getRoles() {
            return roles;
        }
    
        public void setRoles(Set<Role> roles) {
            this.roles = roles;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    ", roles=" + roles +
                    '}';
        }
    }
从Main12类的方法`getName`中将null参数发送到`getName`方法时我将获得null字符串`ofNullable``orElse`方法不会按照我在那里写的做出反应如果您有一些修复方法请让我知道我从未得到过`noFound`字符串或类的字段值的实际名称
英文:

I have question about Java 8 from library java.util.Optional.ofNullable;
I have written following code but I hope that it will return value of field of class. But I keep getting toString method from class. What might be cause of behaving this code.

import static java.util.Optional.ofNullable;
public class Main12 {
public static String getName(User user){
return ofNullable(user).map(User::getName).orElse(&quot;noFound&quot;);
}
public static void main(String[] args) {
User user = new User();
user.setName(&quot;ew&quot;);
System.out.println(user);
}
}

The result that I get from terminal is User{id=null, name=&#39;ew&#39;, age=0, roles=[]}.I hope that I will get value of name field from User class.

public class User {
private Long id;
private String name;
private int age;
private Set&lt;Role&gt; roles = new HashSet&lt;&gt;();
public User(long id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public User(){
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Set&lt;Role&gt; getRoles() {
return roles;
}
public void setRoles(Set&lt;Role&gt; roles) {
this.roles = roles;
}
@Override
public String toString() {
return &quot;User{&quot; +
&quot;id=&quot; + id +
&quot;, name=&#39;&quot; + name + &#39;\&#39;&#39; +
&quot;, age=&quot; + age +
&quot;, roles=&quot; + roles +
&#39;}&#39;;
}
}

User Class field and methods. When I send null parameter of into method getName from Main12 class. I will get null String but orElse from ofNullable not react what I have written there. Please if you have some idea how to fix it let me know.I never get noFound String or real name of field value of Class.

答案1

得分: 3

public static string getName(User user)与你在User类内部定义的getName方法无关。
实际上,它们完全不同。

因此在main方法中,你甚至没有调用带有Optional参数的静态getName方法,因此它根本不会运行。

现在,因为你调用了System.out.println(user),所以会调用toString方法。在这种情况下,Java会自动调用toString方法。就是这样发生的。

Optional.ofNullable会将对该对象的引用(即使为null)包装到Optional包装器中。

我知道,这可能更适合作为注释,而不是答案,但对于评论来说有点太长了。

英文:

public static string getName(User user) has nothing to do with a method getName that you’ve define inside the User class.
In fact they’re completely different

So in the main method you don’t even call the static getName Method with Optionals inside - so it won’t even run.

Now, toString is called because you call System.out.println(user). In this case Java automatically calls toString. That’s what happens.

Optional.ofNullable will “wrap” a reference to the object (even if its null) into the Optional wrapper.

I know, this could be a comment rather than the answer, but its kind of too long for comment.

答案2

得分: 0

你没有在主函数 main 上面定义的静态方法。你可以在你的 User 类中进行以下操作:

public String getName() {
    return Optional.ofNullable(name).orElse("noFound");
}

我必须声明,虽然如此做是可行的,但并不是一个好的实践。如果 name 是可选的,它应该有一个合理的默认值,就像你的 Set 一样。

英文:

You are not invoking the static method you defined above your main anywhere. You could do the following in your User class:

public String getName() {
return Optional.ofNullable(name).orElse(&quot;noFound&quot;);
}

I have to state that this is not a good practice though. If name is really optional, it should default to something sensible, like your Set does.

huangapple
  • 本文由 发表于 2020年8月23日 13:35:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63543755.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定