comparatorreflector
Class ComparatorReflector

java.lang.Object
  |
  +--comparatorreflector.ComparatorReflector
All Implemented Interfaces:
Comparator

public class ComparatorReflector
extends Object
implements Comparator

Version:
$Revision: 1.3 $
Author:
Rafael U. C. Afonso (See LICENCE.txt for more Details)
See Also:
Comparator

Field Summary
private  String attributeName
          beanClass Attribute name that will be used for comparisions.
private  String[] attributes
          Attribute names that will be used for comparisions.
private  Class beanClass
          Base Class who will be compared.
private  Method getterMethod
          Getter Method related to attribute indicated by attributeName.
private  Method[] gettersMethods
          Getters Methods related to attributes indicated by attributes array.
(package private)  Logger logger
           
 
Constructor Summary
ComparatorReflector()
          Default Constructor.
ComparatorReflector(Class beanClass)
          Constructor with class to be used.
ComparatorReflector(Class beanClass, String[] attributes)
          Constructor with class and attribute name.
 
Method Summary
 int compare(Object o1, Object o2)
          Compare two Ojects (so-called from class determined by beanClass) according with attributes determined by attributes array.
private  int compareAttributes(Object o1, Object o2)
          Compare two Objects (not nulls) according their attibutes.
 boolean equals(Object obj)
          Compare this ComparatorReflector with another object (presumably another ComparatorReflector).
 String getAttributeName()
          Deprecated. Use getAttributes instead.
 String[] getAttributes()
           
private  Object getAttributeValue(Object obj, Method method)
          Returns attributevalue in a determinaded object.
 Class getBeanClass()
           
private  Object getFilledObject(Object value)
          Create a beanClass instance with attributeBean filled.
private  Method getGetter(String fieldName)
          Returns a beanClass getter method from a name of attribute.
private  Method getGetterMethod(String attributeName)
          Returns a beanClass getter method from a attribute name.
private  String getGetterMethodName(String name)
          Create a getter method name from a attribute name [Cria o nome de um método getter a partir do nome de um atributo.]
private  List getList(Collection col)
          Create a List from a Collection.
 Object getMax(Collection col)
          Returns item from a Collection that contains maximum value according setted attribute.
 Object getMin(Collection col)
          Returns item from a Collection that contains minimum value according setted attribute.
private  String getSetterMethodName(String name)
          Create a setter method name from a attribute name [Cria o nome de um método setter a partir do nome de um atributo.]
 List getSortedList(Collection col)
          Create a Sorted List according attribute setted by attributeName from a Collection.
 int hashCode()
           
private  boolean isComparable(Class candidateClass)
          Verifies if a class implements Comparable interface.
private  boolean isCompatibles(Object object, Class klass)
          Verify if a certain object is compatible with a certain class.
private  void makeGettersArray()
          Creates the getters methods array to be used, gettersMethods, from attributes name array, attribute.
 Collection search(Collection col, Object key)
          Search for a Object in a Collection.
 Collection searchByAttribute(Collection col, Object key)
          Procura por algum objeto cujo valor do atributo setado seja igual ao do objeto Dado um objeto da mesma classe
 void setAttributeName(String value)
          Change beanClass attribute name that will be used for comparisions.
 void setAttributes(String[] strings)
           
 void setBeanClass(Class value)
          It sets base class that will be compared.
 String toString()
           
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

logger

Logger logger

beanClass

private Class beanClass
Base Class who will be compared. [Classe que será comparada.]

See Also:
Class

attributeName

private String attributeName
beanClass Attribute name that will be used for comparisions. [Nome do atributo que será usado para comparações.]


getterMethod

private Method getterMethod
Getter Method related to attribute indicated by attributeName. [Método getter relacionado ao atributo indicado por attributeName.]

See Also:
Method

attributes

private String[] attributes
Attribute names that will be used for comparisions. [Nome dos atributos que serão usados para comparações.]


gettersMethods

private Method[] gettersMethods
Getters Methods related to attributes indicated by attributes array. [Métodos getters relacionados ao atributos indicados pelo array attributes.]

See Also:
Method
Constructor Detail

ComparatorReflector

public ComparatorReflector()
Default Constructor. [Construtor Padrão.]


ComparatorReflector

public ComparatorReflector(Class beanClass)
                    throws ComparatorReflectorException
Constructor with class to be used. [Construtor com a Classe que será usada.]

Parameters:
beanClass - Class who will be compared. [Classe que será usada.]

ComparatorReflector

public ComparatorReflector(Class beanClass,
                           String[] attributes)
                    throws ComparatorReflectorException
Constructor with class and attribute name. [Constutor com a classe a ser utilizada e o nome do atributo.]

Parameters:
beanClass - Class who will be compared. [Classe base que que será comparada.]
Method Detail

getGetter

private Method getGetter(String fieldName)
                  throws ComparatorReflectorException
Returns a beanClass getter method from a name of attribute. [Retorna um metodo getter de beanClass a partir do nome de um atributo.]

Parameters:
fieldName - A (so-called) beanClass attribute name. [Nome de um (suposto) atributo de beanClass.]
Returns:
Getter method related to fieldName. [Método getter de beanClass referente a fieldName.]
Throws:
ComparatorReflectorException - If there is not a getter method or this method is not public. [Se não existir método getter ou este método não for público.]
See Also:
getGetterMethodName(java.lang.String)

getGetterMethod

private Method getGetterMethod(String attributeName)
                        throws ComparatorReflectorException
Returns a beanClass getter method from a attribute name. [Retorna um metodo getter de beanClass a partir do nome de um attributo.]

Parameters:
attributeName -
Returns:
beanClass getter method from attributeName. [Método getter de beanClass referente a attributeName.]
Throws:
ComparatorReflectorException - If there is not a getter method or this method is not public. [Se não existir método getter ou este método não for público.]
See Also:
getGetter(java.lang.String)

getGetterMethodName

private String getGetterMethodName(String name)
                            throws ComparatorReflectorException
Create a getter method name from a attribute name [Cria o nome de um método getter a partir do nome de um atributo.]

Parameters:
name - Attribute name. [Nome do atibuto.]
Returns:
A getter mehotd name from name. [Nome de um método getter a partir de name.]
Throws:
ComparatorReflectorException - If name was null or empty. [Se nome for null ou vazio.]

getSetterMethodName

private String getSetterMethodName(String name)
                            throws ComparatorReflectorException
Create a setter method name from a attribute name [Cria o nome de um método setter a partir do nome de um atributo.]

Parameters:
name - Attribute name. [Nome do atibuto.]
Returns:
A setter mehotd name from name. [Nome de um método setter a partir de name.]
Throws:
ComparatorReflectorException - If name was null or empty. [Se nome for null ou vazio.]
See Also:
getGetterMethodName(java.lang.String)

getAttributeValue

private Object getAttributeValue(Object obj,
                                 Method method)
                          throws ComparatorReflectorException
Returns attributevalue in a determinaded object. [Retorna o valor do atributo setado num determinado objeto.]

Parameters:
obj - Object (beanClass instance) from where will be extracted setted attribute value. [Objeto (instância de banClass) de onde será extraído o valor do atributo setado.]
Returns:
Attribute value in obj. [Valor do atributo em obj.]
Throws:
ComparatorReflectorException - If getter method is not public or it has arguments or it throws a exception. [Se o método getter não for publico ou tiver argumentos ou disparar uma exceção.]

getList

private List getList(Collection col)
Create a List from a Collection. [Gera um Lista a partir de uma Collection.]

Parameters:
col - Source Collection. [Colecao inicial.]
Returns:
List created from col. [Lista gerada a partir de col.]

isComparable

private boolean isComparable(Class candidateClass)
Verifies if a class implements Comparable interface. [Verifica se uma determinada classe implementa a interface Comparable.]

Parameters:
candidateClass - analisable class. [Classe a ser analisada.]
Returns:
true if class is Comparacle itself or implements it. false otherwise. [true se a classe for a própria Comparable ou implementá-la. false caso contrário.]
See Also:
Comparable

isCompatibles

private boolean isCompatibles(Object object,
                              Class klass)
Verify if a certain object is compatible with a certain class. [Verifica se um certo objeto é compatível com certa classe.]

Parameters:
object - Object to be analized [Objeto a ser analizado.]
klass - Class to be compared with object. [Classe a ser comparada com object.]
Returns:
true if object is a instance of klass or its derivated or if klass is a primitive and class object is its respective wrapper; false otherwise. [true se object for uma instancia de klass ou alguma derivada dessa ou se klass for uma primitiva e a classe de object for uma instancia de seu respectivo wrapper.]

getFilledObject

private Object getFilledObject(Object value)
                        throws ComparatorReflectorException
Create a beanClass instance with attributeBean filled. [Cria uma instancia de beanClass com attributeBean preenchido.]

Parameters:
value - attributeBean value [Valor a ser atribuido a attributeBean.]
Returns:
beanClass instance with attributeBean filled. [Instancia de beanClass com attributeBean preenchido.]
Throws:
ComparatorReflectorException - If it is not possible create a beanClass Instance or setter method referent to attributeBean is not public or this setter method throws a Exception. [Se nao for possivel criar uma instancia de beanClass ou se não existir metodo setter referente a attributeBean ou se este metodo setter disparar uma excecao.]

makeGettersArray

private void makeGettersArray()
Creates the getters methods array to be used, gettersMethods, from attributes name array, attribute.

Throws:
ComparatorReflectorException - If there is not a getter method or this method is not public. [Se não existir método getter ou este método não for público.]

compareAttributes

private int compareAttributes(Object o1,
                              Object o2)
Compare two Objects (not nulls) according their attibutes.

Parameters:
o1 - First Object (not nulls) to be compared.
o2 - Second Object (not nulls) to be compared with o1.
Returns:
  1. If all selected attributes are equals: it is returned 0;
  2. If a attribute value from first object is not null and value from second object is null: How first value is "bigger", it is returned +1.
  3. If a attribute value from first object is null and value from second object is not null: How second value is "bigger", it is returned -1.
  4. If a attribute value is not null in both objects: these values are cast to java.lang.Comparable interface and result got is value from compareTo() method.
See Also:
Comparable.compareTo(java.lang.Object)

getAttributes

public String[] getAttributes()
Returns:
Attribute names that will be used for comparisions. [Nome dos atributos que serão usados para comparações.]

getAttributeName

public String getAttributeName()
Deprecated. Use getAttributes instead.

Returns:
beanClass Attribute name that will be used for comparisions. [Nome do atributo que será usado para comparações.]

getBeanClass

public Class getBeanClass()
Returns:
Base Class who will be compared. [Classe que será comparada.]

setAttributes

public void setAttributes(String[] strings)
Parameters:
strings - Attribute names that will be used for comparisions. [Nome dos atributos que serão usados para comparações.]

setAttributeName

public void setAttributeName(String value)
                      throws ComparatorReflectorException
Change beanClass attribute name that will be used for comparisions. [Altera o nome do atributo de beanClass que servira de base para comparacao.]

Parameters:
value - A beanClass attribute name that will be used for comparisions. [Nome de um dos atributos de beanClass que servira de base para comparacao.]
Throws:
ComparatorReflectorException - If there is not difinied class; If there is not a getter method for attribute indicated by value. It can indicate that there is not this attribute. [Se não há classe definida; Se não existir um método getter para o atributo indicado por value. Isto pode indicar que tal atributo simplesmente não existe.]

setBeanClass

public void setBeanClass(Class value)
                  throws ComparatorReflectorException
It sets base class that will be compared. As Collateral effect, it cleans comparsion attribute name. [Altera a Classe base que será comparada. Como efeito colateral, limpa o nome do atributo de comparação.]

Parameters:
value - Base Class who will be compared. [Classe que será comparada.]
ComparatorReflectorException

getMax

public Object getMax(Collection col)
Returns item from a Collection that contains maximum value according setted attribute. [Retorna o item de uma colecao que contem o valor máximo de acordo com o atriburo setado.]

Parameters:
col - Collection where will be make search. [Colecao onde será feita a busca.]
Returns:
col item that contains maximum value according setted attribute. [Item de col que contem o valor máximo de acordo com o atributo setado.]

compare

public int compare(Object o1,
                   Object o2)
            throws ComparatorReflectorException
Compare two Ojects (so-called from class determined by beanClass) according with attributes determined by attributes array. [Compara dois objetos (presumivelmente da classe determinada pelo atributo beanClass) de acordo com o atributos determinado por array de Atributos.]

Specified by:
compare in interface Comparator
Parameters:
o1 - First Object (so-called a beanClass instance). [Primeiro Objeto (presumivelmente uma instancia de beanClass).]
o2 - Object that will be compared with o1 (so-called a beanClass instance too). [Objeto a ser comparado com o1 (presumivelmente uma instancia de beanClass também).]
Returns:
  1. Both o1 an o2 are null: returns 0; [Tanto o1 quanto o2 são null: retorna 0;]
  2. o1 is not null and o2 is null: returns +1, because o1 will be "bigger" than o2. [o1 é não null e o2 é null: retorna +1, pois o1 seria "maior" que o2]
  3. o1 is null and o2 is not null: returns -1, because o1 will be "lesser" than o2; [o1 é nulo e o2 é não nulo: retorna -1, pois o1 seria "menor" que o2]
  4. both o1 and o2 are not null: result is going to depend of attribute determined by values of attributes determinated by attributes array: [o1 e o2 não são nulos: O resultado vai depender dos valores dos atributos determinados pelo array de atributos:]
    1. Both value1 and value2 are null: returns 0; [Tanto valor1 e valor2 são nulos: retorna 0;]
    2. value1 is not null and value2 is: return +1, because value1 will be "bigger" than value2; [valor1 é não nulo e valor2 é nulo: retorna +1, pois valor1 seria "maior" que valor2;]
    3. value1 is null and value2 is not: return -1, because value1 will be "lesser" than value2; [valor1 é nulo e valor2 é não nulo: retorna -1, pois valor1 seria "menor" que valor2;]
    4. Both value1 and value2 are not null: value1 is compared with value2 according these class. [valor1 e valor2 não são nulos: valor1 é comparado com valor2 de acordo com suas classes.]
ComparatorReflectorException
See Also:
compareAttributes(java.lang.Object, java.lang.Object)

getMin

public Object getMin(Collection col)
Returns item from a Collection that contains minimum value according setted attribute. [Retorna o item de uma colecao que contem o valor mínimo de acordo com o atriburo setado.]

Parameters:
col - Collection where will be make search. [Colecao onde será feita a busca.]
Returns:
col item that contains maximum value according setted attribute. [item de col que contem o valor mínimo de acordo com o atributo setado.]

getSortedList

public List getSortedList(Collection col)
Create a Sorted List according attribute setted by attributeName from a Collection. [Cria uma lista ordenada de acordo com atributo indicado por attributeName a partir de uma Coleção.]

Parameters:
col - Source Collection [Coleção base]
Returns:
Sorted List according attribute setted by attributeName [Lista ordenada de acordo com o atributo indicado por attributeName.]

search

public Collection search(Collection col,
                         Object key)
                  throws ComparatorReflectorException
Search for a Object in a Collection. Of course, this object must be a beanClass object and search will be based on attribute setted by attributteName. [Busca por um determinado objeto em uma coleção. Naturalmente esta objeto deve uma instancia de beanClass e a busca será feita de acordo com o atributo indicado por attributeName]

Parameters:
col - Collection where will be made the search. [Coleção onde será feita a busca.]
key - beanClass instance where [Objeto procurado]
Returns:
Collection Object equivalent to key or null if this object does not exist. [Objeto da Coleção equivalente a key ou null se este objeto não existir.]
Throws:
ComparatorReflectorException - If key is not from same class (or sub-class) definied by beanClass [Se key não for da mesma classe (ou sub-classe) definida por beanClass.]
See Also:
getBeanClass(), getAttributeName()

searchByAttribute

public Collection searchByAttribute(Collection col,
                                    Object key)
                             throws ComparatorReflectorException
Procura por algum objeto cujo valor do atributo setado seja igual ao do objeto Dado um objeto da mesma classe

Parameters:
col - Colection where will be made the search. [Colecao onde será feita a busca.]
key - Objeto da mesma classe do objeto setado
Returns:
Objeto cujo atributo setado tenha o mesmo valor de key.
Throws:
ComparatorReflectorException - If it is not possible create a beanClass Instance or setter method referent to attributeBean is not public or this setter method throws a Exception or if key class is not equals than attributeBean class [Se nao for possivel criar uma instancia de beanClass ou se não existir metodo setter referente a attributeBean ou se este metodo setter disparar uma excecao.]

equals

public boolean equals(Object obj)
Compare this ComparatorReflector with another object (presumably another ComparatorReflector). [Compara este ComparatorReflector com um outro objeto (presumivelmente outro ComparatorReflector).]

Specified by:
equals in interface Comparator
Overrides:
equals in class Object
Parameters:
obj - Object (presumably another ComparatorReflector) that this ComparatorReflector compared. [Objeto (presumivelmente outro ComparatorReflector) com o qual este ComparatorReflector será comparado.]
Returns:
true in these conditions: 1) obj is exactly the same instance of this ComparatorReflector; 2) obj is a instance of ComparatorReflector with same beanClass and attributeName of this ComparatorReflector. false otherwise. [true nas seguites condições: 1) obj é exatamente a mesma instancia deste ComparatorReflector; 2) obj é uma instancia de ComparatorReflector com o mesmo beanClass e attributeName deste ComparatorReflector. Caso nenhuma das duas condições sejam satisfeitas, é retornado false.]

hashCode

public int hashCode()
Overrides:
hashCode in class Object
Returns:
this ComparatorReflector hash code. [Código hash deste ComparatorReflector]
See Also:
Object.hashCode()

toString

public String toString()
Overrides:
toString in class Object
Returns:
String with this ComparatorReflector attributes in this format: "Class: [beanClass], Attributes: [attributes]". [String com os atributos desta ComparatorReflector no seguinte formato: "Class: [beanClass], Attributes: [attributes]".]