Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / Java [игнор отключен] [закрыт для гостей] / equals / 14 сообщений из 14, страница 1 из 1
26.07.2007, 14:06:41
    #34685873
_help_
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
equals
есть два бина одного типа. надо их сравнить.
понятно что надо переопределить equals(), но не радует перспектива писать кучу if для кучи филдов.. есть какой-нибудь более красивый способ?
...
Рейтинг: 0 / 0
26.07.2007, 14:55:32
    #34686153
wpn
wpn
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
equals
use IDEA!
...
Рейтинг: 0 / 0
26.07.2007, 15:01:46
    #34686182
expp
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
equals
CompareToBuilder

BeanUtils
...
Рейтинг: 0 / 0
26.07.2007, 15:12:39
    #34686236
_help_
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
equals
wpnuse IDEA!

не понял чем идея может помочь
...
Рейтинг: 0 / 0
26.07.2007, 15:21:35
    #34686288
wpn
wpn
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
equals
_help_ wpnuse IDEA!

не понял чем идея может помочь
Она может за тебя имплементировать equals & hashCode.
...
Рейтинг: 0 / 0
26.07.2007, 15:32:32
    #34686333
_help_
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
equals
wpn _help_ wpnuse IDEA!

не понял чем идея может помочь
Она может за тебя имплементировать equals & hashCode.

точно! :)
спасибо.
...
Рейтинг: 0 / 0
26.07.2007, 15:34:13
    #34686342
_help_
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
equals
exppCompareToBuilder

BeanUtils

в BeanUtils есть конечно BeanComparator, но по крайней мере в используемой версии 1.6, насколько я понял, можно сравнивать только по одному проперти за раз. поправьте если не прав.
...
Рейтинг: 0 / 0
26.07.2007, 15:38:55
    #34686356
Leonidv
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
equals
wpnuse IDEA! или Eclipse.
...
Рейтинг: 0 / 0
26.07.2007, 16:57:03
    #34686733
wpn
wpn
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
equals
Leonidv wpnuse IDEA! или Eclipse.
т.к. автор уже нашел ответ, можем достать перчатки и побоксировать

эклипс - суксь. :)
...
Рейтинг: 0 / 0
26.07.2007, 17:01:44
    #34686759
_help_
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
equals
wpn Leonidv wpnuse IDEA! или Eclipse.
т.к. автор уже нашел ответ, можем достать перчатки и побоксировать

эклипс - суксь. :)

я неудовлетворён ответом :)
генерация идеей это конечно хорошо, но было бы лучше что-нибудь динамическое, не зависящее от пропертей.
хотелось бы услышать ответ насчёт BeanComporator.
...
Рейтинг: 0 / 0
26.07.2007, 17:09:32
    #34686802
Timm
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
equals
_help_есть два бина одного типа. надо их сравнить.
понятно что надо переопределить equals(), но не радует перспектива писать кучу if для кучи филдов.. есть какой-нибудь более красивый способ?
почему будет куча if'ов для кучи филдов?
достаточно одного if.
+ имхо, делать динамические компараторы чаще всего не нужно.
PS. если поискать в гугле , можно найти готовый, для multi-fields.
...
Рейтинг: 0 / 0
26.07.2007, 17:10:51
    #34686807
expp
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
equals
вопрос как сравнить бины коммонсами ?

может сам гланешь ?
...
Рейтинг: 0 / 0
26.07.2007, 17:22:24
    #34686866
_help_
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
equals
exppвопрос как сравнить бины коммонсами ?

может сам гланешь ?

глянул:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
/*
 * $Header: /home/cvspublic/jakarta-commons/beanutils/src/java/org/apache/commons/beanutils/BeanComparator.java,v 1.4 2003/01/15 21:59:38 rdonkin Exp $
 * $Revision: 1.4 $
 * $Date: 2003/01/15 21:59:38 $
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Commons", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

 package  org.apache.commons.beanutils;

 import  java.io.Serializable;
 import  java.util.Comparator;
 import  org.apache.commons.beanutils.PropertyUtils;
 import  org.apache.commons.collections.comparators.ComparableComparator;

/**
 * Allows you to pass the name of a method in and compare two beans.
 *
 * @author     <a href"mailto:epugh@upstate.com">Eric Pugh</a>
 */
 public   class  BeanComparator  implements  Comparator, Serializable {

     private  String property;
     private  Comparator comparator;

    /**
     * Creates a Bean comparator that calls the property specified 
     * on the objects.
     * If you pass in a null, the BeanComparator defaults to comparing
     * based on the natural order, that is java.lang.Comparable.
     *
     * @param property String name of bean property
     */
     public  BeanComparator( String property ) {
         this ( property, ComparableComparator.getInstance() );
    }

    /**
     * Creates a comparator that compares objects based on the method 
     * name of two JavaBeans.
     *
     * @param property String method name to call to compare 
     * @param comparator      Comparator to call afterwords!
     */
     public  BeanComparator( String property, Comparator comparator ) {
        setProperty( property );
         this .comparator = comparator;
    }

    /**
     * Sets the method to be called to compare two JavaBeans
     *
     * @param property String method name to call to compare 
     */
     public   void  setProperty( String property ) {
         this .property = property;
    }


    /**
     * Gets the property attribute of the BeanComparator
     *
     * @return String method name to call to compare
     */
     public  String getProperty() {
         return  property;
    }


    /**
     * Gets the Comparator being used to compare beans.
     */
     public  Comparator getComparator() {
         return  comparator;
    }


    /**
     * Compare two JavaBeans by their shared property.
     *
     * @param  o1 Object The first bean to get data from to compare against
     * @param  o2 Object The second bean to get data from to compare
     * @return int negative or positive based on order
     */
     public   int  compare( Object o1, Object o2 ) {
         try  {
            Object value1 = PropertyUtils.getProperty( o1, property );
            Object value2 = PropertyUtils.getProperty( o2, property );
             return  comparator.compare( value1, value2 );
        }
         catch  ( Exception e ) {
             throw   new  ClassCastException( e.toString() );
        }
    }

}



для тех кто в танке повторю вопрос

_help_
по крайней мере в используемой версии 1.6, насколько я понял, можно сравнивать только по одному проперти за раз. поправьте если не прав.


я же хочу чтобы была проверка сразу по всем филдам и чтобы не надо было их вручную перечислять.
...
Рейтинг: 0 / 0
26.07.2007, 17:50:49
    #34687000
expp
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
equals
...
Рейтинг: 0 / 0
Форумы / Java [игнор отключен] [закрыт для гостей] / equals / 14 сообщений из 14, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]