MyClass.java Source code

Java tutorial

Introduction

Here is the source code for MyClass.java

Source

import java.lang.reflect.Field;

class MyClass {
    private String name = "Unknown";

    public MyClass() {
    }

    public String toString() {
        return "name=" + this.name;
    }
}

public class Main {
    public static void main(String[] args) {
        Class<MyClass> my = MyClass.class;
        try {
            MyClass p = my.newInstance();
            Field nameField = my.getDeclaredField("name");
            nameField.setAccessible(true);
            String nameValue = (String) nameField.get(p);
            System.out.println("Current name is " + nameValue);
            nameField.set(p, "abc");
            nameValue = (String) nameField.get(p);
            System.out.println("New name is " + nameValue);
        } catch (InstantiationException | IllegalAccessException | NoSuchFieldException | SecurityException
                | IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}