ClassToInstanceMap示例

x33g5p2x  于2022-10-05 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(467)

示例测试类

class Person {
    private String name;

    public Person(String name) {
        super();
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("name", name)
                .toString();
    }
}

class Jobs {
    private String jobName;

    public Jobs(String jobName) {
        super();
        this.jobName = jobName;
    }

    public String getJobName() {
        return jobName;
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("jobName", jobName)
                .toString();
    }
}

class Address {
    private String streetName;

    public Address(String streetName) {
        super();
        this.streetName = streetName;
    }

    public String getStreetName() {
        return streetName;
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("streetName", streetName)
                .toString();
    }
}

ClassToInstanceMap

@Test
public void classToINstanceMap_example () {

    Person person = new Person("Jackson");
    Jobs jobs = new Jobs("IT person");
    Address address = new  Address("505 Williams Street");

    ClassToInstanceMap<Object> classToInstanceMap = MutableClassToInstanceMap.create();
    classToInstanceMap.put(Person.class, person);
    classToInstanceMap.put(Jobs.class, jobs);
    classToInstanceMap.put(Address.class, address);

    logger.info(classToInstanceMap);

    assertEquals("IT person", classToInstanceMap.getInstance(Jobs.class).getJobName());
}

输出

{
    class com.levelup.java.guava.ClassToInstanceMapExample$Jobs=Jobs{jobName=IT person},
    class com.levelup.java.guava.ClassToInstanceMapExample$Person=Person{name=Jackson},
    class com.levelup.java.guava.ClassToInstanceMapExample$Address=Address{streetName=505 Williams Street}
}

相关文章