MyClass.java Source code

Java tutorial

Introduction

Here is the source code for MyClass.java

Source

import java.lang.reflect.Field;

class MyClass {
    public String name = "Unknown";

    public MyClass() {
    }

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

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