Skip to content

Instantly share code, notes, and snippets.

@fitorec
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fitorec/38b005baa55f99a81fb2 to your computer and use it in GitHub Desktop.
Save fitorec/38b005baa55f99a81fb2 to your computer and use it in GitHub Desktop.
PruebaGetClass.java
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class PruebaGetClass {
String atributo_1 = "valor 1";
String atributo_2 = "valor 2";
String valor_x = null;
public String nombreClase() {
return this.getClass().getSimpleName();
}
public void imprimirAtributos() {
Field[] fields = this.getClass().getDeclaredFields();
for(Field field : fields) {
try {
String fieldName = field.getName();
Object fieldValue = field.get(this);
System.out.println(fieldName + ":" + fieldValue);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
///
/**
* Constructores normales
*
* @param atributo_value
*/
public PruebaGetClass(String atributo_value) {
this.atributo_1 = atributo_value;
}
public PruebaGetClass(){
}
/**PruebaGetClass
* Devuelve una instancia de PruebaNewInstance dinamica a partir de un constructor con atributos
* @param atributo_value
* @return
*/
static public PruebaNewInstance constructor(String atributo_value) {
try {
return PruebaNewInstance.class.getConstructor(String.class).newInstance(atributo_value);
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
return null;
}
/**
* Devuelve una instancia de PruebaNewInstance dinamica a a patir del constructor vacio
*
* @return
*/
static public PruebaNewInstance constructor() {
try {
return PruebaNewInstance.class.newInstance();
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | SecurityException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
PruebaGetClass prueba = new PruebaGetClass();
//Mostraando el nombre de clase
System.out.print(prueba.nombreClase());
//Listando atributos
prueba.imprimirAtributos();
//
// Creando un objeto desde un constructor dinamico
PruebaNewInstance prueba2 = PruebaGetClass.constructor("val_atrib_1 constructor Dinamico");
System.out.println(prueba2.atributo_1);
//
PruebaNewInstance prueba3 = PruebaGetClass.constructor();
System.out.println(prueba3.atributo_1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment