@Test public void testUnmarshallFromParentToChild() throws JAXBException { Person person = new Person(); int age = 30; String name = "Foo"; person.name = name; person.age= age; // Marshalling JAXBContext context = JAXBContext.newInstance(person.getClass()); Marshaller marshaller = context.createMarshaller(); StringWriter writer = new StringWriter(); marshaller.marshal(person, writer); String outString = writer.toString(); assertTrue(outString.contains("</person")); // Unmarshalling context = JAXBContext.newInstance(Person.class, RecieverPerson.class); Unmarshaller unmarshaller = context.createUnmarshaller(); StringReader reader = new StringReader(outString); RecieverPerson reciever = (RecieverPerson)unmarshaller.unmarshal(reader); assertEquals(name, reciever.name); assertEquals(age, reciever.age); }
Person person = new Person(); Field[] fields = person.getClass().getFields(); for(Field field : fields){ DesiredField annotation = field.getAnnotation(DesiredField.class); if( annotation != null ){ // This is desired field now do what you want } }
Person obj = new Person("qew"); Method methodGetAchievements = obj.getClass().getMethod("getAchievments"); Object achievements = methodGetAchievements.invoke(obj); Method methodAmount = achievements.getClass().getMethod("amount"); int amount = (int) methodAmount.invoke(achievements);
Person p = new Person(); Class<Person> clazz = p.getClass(); Method m = clazz.getMethod("myMethod", String.class); m.invoke(p, "my string argument");
public static void main(String args[]) { Person p = new Person("Elliott", 37); Field[] fields = p.getClass().getDeclaredFields(); for (Field f : fields) { try { f.setAccessible(true); String name = f.getName(); String val = f.get(p).toString(); System.out.printf("%s = %s%n", name, val); } catch (Exception e) { e.printStackTrace(); } } }
Person personobject = new Person(6, "Test"); MaxLength maxLengthAnnotation; Method[] methods = personobject.getClass().getDeclaredMethods(); for (Method method : methods) { if (method.getName().startsWith("get")) { // check added to avoid run time exception if(method.isAnnotationPresent(MaxLength.class)) { maxLengthAnnotation = method.getAnnotation(MaxLength.class); System.out.println(method.getName().substring(3) + " " + maxLengthAnnotation.length()); }; } }
public class Main { public static void main(String[] args) { Person a = new Person("smith", "joe", 25, 1.57, "male"); Person b = new Person("davis", "sian", 18, 1.73, "female"); List<Person> persons = new ArrayList<Person>(); persons.add(a); persons.add(b); for(Person p : persons){ System.out.format("%s %s %s %d %.2f %s", p.getClass().getName(), p.getSurname(), p.getForname(), p.getAge(), p.getHeight(), p.getGender()); System.out.println(); } } }