src/com/oop/Person.java
package com.oop; public class Person { private String name; private String phone; public Person(String name, String phone) { this.name = name; this.phone = phone; } public String getName() { return name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
There are two private fields - name and phone. Name can be only set using constructor. We cannot modify the private variable in classic way. This can be done using reflection.
src/com/run/Run.java
package com.run; import java.lang.reflect.Field; import java.lang.reflect.Method; public class Run { public static void main(String[] args) { try { Class c1 = Class.forName("com.oop.Person"); Object p1 = c1.getConstructor(String.class, String.class).newInstance("John", "3242342"); Method m1 = c1.getDeclaredMethod("getName"); Object result = m1.invoke(p1); System.out.println(result); Field nameField = c1.getDeclaredField("name"); nameField.setAccessible(true); nameField.set(p1,"Derrek"); result = m1.invoke(p1); System.out.println(result); } catch (Exception e) { System.out.println("Exception: " + e.toString()); } } }
Using getDeclaredField instead getField let us access private and protected variables. Setting accessible flag allows us to modify it. Finally the output looks like:
John
Derrek
Brak komentarzy:
Prześlij komentarz