Boa tarde colegas,
Gostaria de uma opinião de voces sobre uma classe que precisei desenvolver. Estou em um projeto utilizando EJB e JSF.
Precisamos validar os campos verificando se os atributos obrigatórios foram informados.
Atualmente estou fazendo isto na classe controle e to pensando em passar esta validação para o EJB.
Resumindo, já existe várias linhas verificando se o atributo está preenchido então utilizei Reflection.
Fiz uma leitura na classe modelo, onde tiver nullable=false (nas anotações) ele verifica se o atributo está preenchido.
Gostaria da opinião e sugestões no que for mais indicado e se caso tenha reinventado a roda favor me avisem.
package br.com.trackbus.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
/**
* ValidaPreenchimento.java - Le atributos de [instancia] validando os
* requeridos. (Nullable=false)
*
* @author Junior Carvalho (joseadolfojr@gmail.com)
* @see 18/01/2011
*/
@SuppressWarnings("unchecked")
public class ValidaPreenchimento<T> {
private Class classe;
private T instancia;
private String mensagem;
private Boolean retorno = false;
public ValidaPreenchimento(T instancia_) {
if (instancia_ == null) {
this.retorno = false;
this.mensagem = "";
} else {
this.instancia = instancia_;
this.classe = instancia_.getClass();
this.mensagem = "";
this.Validar();
// se tiver mensagem, formatamos mensagem e retorno=false
if (this.mensagem.trim().length() > 0) {
this.retorno = false;
this.mensagem = this.mensagem.trim();
if (this.mensagem.endsWith(","))
this.mensagem = this.mensagem.substring(0, this.mensagem
.length() - 1);
this.mensagem = "Campo(s) " + this.mensagem
+ " com preenchimento obrigatório.";
} else {
this.mensagem = "";
this.retorno = true;
}
}
}
public void Validar() {
Field fieldList[] = getClasse().getDeclaredFields();
for (Field f : fieldList) {
// atributo de serialização não verificamos...
if (f.getName().equals("serialVersionUID"))
continue;
// para acessar atributo private...
f.setAccessible(true);
// pegando o valor do atributo...
Object value = null;
try {
value = f.get(getInstancia());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
// comparando valor lido...
Boolean p;
if (value == null)
p = false; // sem valor
else {
if (value.toString().trim().length() == 0)
p = false;
else
p = true;
}
// false = caso coluna nao tenha anotação nullable...
Boolean nullAble = false;
Annotation[] anotacoes = f.getAnnotations();
for (Annotation an : anotacoes) {
nullAble = an.toString().contains("nullable=false");
}
// Regra...
if (nullAble) // tem nullable=false, preenchimento obrigatório
if (!p) // nao preencheu
setMensagem(getMensagem() + f.getName() + ", ");
}
}
public String getMensagem() {
return mensagem;
}
public void setMensagem(String mensagem) {
this.mensagem = mensagem;
}
public Boolean getRetorno() {
return retorno;
}
public void setRetorno(Boolean retorno) {
this.retorno = retorno;
}
public Class getClasse() {
return classe;
}
public void setClasse(Class classe) {
this.classe = classe;
}
public T getInstancia() {
return instancia;
}
public void setInstancia(T instancia) {
this.instancia = instancia;
}
}
Para testar…
public static void main(String[] args) {
MinhaClasse minhaClasse = new MinhaClasse ();
ValidaPreenchimento<MinhaClasse> valid = new ValidaPreenchimento<MinhaClasse>(minhaClasse);
if(!valid.getRetorno()){
System.out.println(valid.getMensagem());
}else
System.out.println("ok");
}
Att
Júnior Carvalho