如何在Java中修剪其某些字段的对象? [英] How to prune an object of some of its fields in Java?

查看:323
本文介绍了如何在Java中修剪其某些字段的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个类型为Object的对象obj,这样System.out.println(obj)会生成{a=Some text, b=Some more text, c=Even more text}.

Suppose we have an object obj of type Object such that System.out.println(obj) produces {a=Some text, b=Some more text, c=Even more text}.

现在,我们要创建一个仅{a=Some text}的新对象obj2(即,从obj删除字段bc).因此,我们定义类A如下:

Now we want to make a new object obj2 that is just {a=Some text} (i.e., the fields b and c are pruned from obj). So we define a class A as follows:

class A {
    String a;
}

然后我们按以下步骤初始化obj2:

Then we initialize obj2 as follows:

A obj2 = (A) obj.

不幸的是,这样做时我遇到了运行时错误.

Unfortunately, I get a run time error when doing this.

问题:如上所述,我们如何定义obj2?

Question: How do we define obj2 as outlined above?

推荐答案

假定您在class A

使用字段f1

class A中声明这样的方法

public B getTrimmedObject()

设置A中B的必填字段.

例如设置f1并返回B对象

Other way : use composition over inheritance .B将成为A的成员,您只需从A. B中获取B.In this case split fields between A and B and avoid duplication.

Other way : use composition over inheritance.B will become member of A and you can simply get B from A. In this case split fields between A and B and avoid duplication.

f1将成为B的一部分,而B,f2,f3将成为A的一部分.构造函数将通过B设置f1的值,而f2,f3则使用常规初始化进行设置

f1 will be part of B and B,f2,f3 will be part of A. A Constructor will set f1 value through B and f2,f3 are set with normal initialization

示例代码:

public class A{
    private B b;
    private String f2;
    private String f3;

    public A(String f1,String f2,String f3){
        b = new B(f1);
        this.f2 = f2;
        this.f3 = f3;
        System.out.println("In A->B:"+getB().getF1()+":A:f2:"+f2+":A:f3:"+f3);
    }
    public B getB(){
        return this.b;
    }
    public static void main(String args[]){
        if (args.length < 3) {
            System.out.println("Usage: java A str1 str2 str3");
            return;
        }
        A a = new A(args[0],args[1],args[2]);

    }

}
class B{
    private String f1;
    public B(String f1){
        this.f1 = f1;
    }
    public String getF1(){
        return this.f1;
    }
}



java A apple banana camel

 In A->B:apple:A:f2:banana:A:f3:camel

这篇关于如何在Java中修剪其某些字段的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆