繁体   English   中英

Java中基于权重的对象匹配(不是内存中对象的实际权重)

[英]Weight-based Object Matching in Java (not the actual weight on an object in memory)

我试图找到一种不错的设计来加权对象中的属性。

例如;

对象“ A”可能有4个字段,每个字段的权重都不同(对于此示例,字段将被平均加权)。 找到一个相同类型的新对象,并且仅其中一些字段相同。 对于此示例,对象“ B”的2个字段等于对象“ A”。 因此它与对象“ A”相同50%。

代码中的另一个示例;

Class Person{

    {Weight = 60}
    String name;

    {Weight = 20}
    String address;

    {Weight = 20}
    int age

    int weightBasedEqual(Person a, Person b)
    {
        //based on my weights I want to pass two Person objects and get a weighted value back
        //So in my example the names are the same but the two other fields are incorrect, 
        //but based on my weights it will return 60 as the match, where 100 was the top weight. 

        return value

   }

} 

我想说一种方法,该对象的某些值相同,但是属性的权重可以更改。

我希望这是有道理的,因此简而言之,我想提供一个解决方案,其中可以对一个对象的每个属性进行加权,并且当在两个对象上完成相等操作时,将返回一个值,表明该对象是那个值。

您可以创建和注释,这些注释将在运行时可用:

@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({FIELD})
@Inherited
@interface Weight{
    int value();
}

然后您可以注释课程的字段

public class TestBean{

    @Weight(20)
    int field1;

    @Weight(80)
    int field2;
}

并且比将执行某事的实现方法将带有该注释的所有字段:

int weightBasedEqual(Person a, Person b)

        // For each field annotated with @Weight
        for(Field field : a.getClass().getDeclaredFields()){

            if(field.isAnnotationPresent(Weight.class)){

                // Get the weight
                int weight = field.getAnnotation(Weight.class).value();

                Object valueFromA = field.get(a); // Get field value for A 
                Object valueFromB = field.get(b); // Get field value for B
                // Compare the field value from 'a' and 'b' here and do with the weight whatever you like   
            }
       }
        return result;
    }
}

这是一种计算weightBasedEqual的方法。

public class Person {
    String name;
    static int nameWeight = 60;

    String address;
    static int addressWeight = 20;

    int age;
    static int ageWeight = 20;

    public int weightBasedEqual(Person a, Person b) {
        int value = 0;
        if (a.name.equalsIgnoreCase(b.name)) {
            value += nameWeight;
        }

        if (a.address.equalsIgnoreCase(b.address)) {
            value += addressWeight;
        }

        if (a.age == b.age) {  value += ageWeight; }
        return value;
    }

    public int weightBasedEqual(Person b) {
        return weightBasedEqual(this, b);
    }
}

该功能通过在(且仅当)字段完全匹配时为每个字段添加权重来工作。 如所写,该函数将返回0、20、40、60、80或100。

请注意,每个Person类都有一个nameWeight,addressWeight和ageWeight,因为它是静态的。

我添加了一个第二个weightBasedEqual,一个人,因为有时候可能需要计算现有对象的基于权重的均等。

暂无
暂无

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

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