jeudi 18 juin 2020

Get class properties from class absolute path using reflection in java

im generating new classes using file package but when i want to get the class properties using reflection it doesn't work and it gave me the error bellow but when i refresh my package by clicking on the right button of my mouse and i click on refresh and i rerun my function it works. So now i think that i need to change my method to get those properties by using absolut path instead of name of package.

my code

import java.lang.reflect.Field;

public class Main7{
    public static void main(String[] args) throws Exception {

        Class classe = Class.forName("com.test.model.Client");
        // affiche tous les attributs
        System.out.println("Attributs -------------------------------------");
        for (Field attribut : classe.getDeclaredFields()) {
           // System.out.print("   "+Modifier.toString(attribut.getModifiers()));
            String type = attribut.getType().getName();
            if(type.contains(".")) {
                String[] tab = type.split("\\.");
                type=tab[2];
            }
            System.out.println(type+" "+attribut.getName());
        }

    }
}

error

Exception in thread "main" java.lang.ClassNotFoundException: ma.dxc.generator.model.Clientz
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at generatortest.Main7.main(Main7.java:16)

good result

Attributs -------------------------------------
long id
String name
String city




Aucun commentaire:

Enregistrer un commentaire