Last active
August 25, 2021 14:48
-
-
Save atsushi-kitazawa/32a89059e26e1bdfed762d145f36f9df to your computer and use it in GitHub Desktop.
java reflection sample of super class fields.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import java.lang.reflect.Field; | |
import com.example.pojo.Device; | |
import com.example.pojo.Keyboard; | |
import com.example.pojo.iPhone; | |
public class Main { | |
public static void main(String[] args) { | |
accessClassMetaData(buildKeyboard()); | |
accessClassMetaData(buildiPhone()); | |
} | |
private static void accessClassMetaData(Device d) { | |
Class<?> clazz = d.getClass(); | |
System.out.println("===" + clazz.getSimpleName() + "==="); | |
System.out.println(clazz); | |
for (Field f : clazz.getDeclaredFields()) { | |
System.out.println(" " + f.getName()); | |
} | |
Class<?> superClass; | |
while (!(superClass = clazz.getSuperclass()).equals(Object.class)) { | |
System.out.println(superClass); | |
for (Field f : superClass.getDeclaredFields()) { | |
System.out.println(" " + f.getName()); | |
} | |
clazz = clazz.getSuperclass(); | |
} | |
} | |
private static Device buildKeyboard() { | |
Keyboard keyboard = new Keyboard(); | |
keyboard.setId(0); | |
keyboard.setName("HHKB"); | |
keyboard.setType("US"); | |
return keyboard; | |
} | |
private static Device buildiPhone() { | |
iPhone i = new iPhone(); | |
i.setId(10); | |
i.setName("apple"); | |
i.setOS("ios"); | |
i.setVersion("11"); | |
return i; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment