Know if a class is native to JAVA or created by the User?

5

I've created a method that uses reflection to execute getters over an object, but I need to know if the class is native to JAVA, for example: java.lang.String , or if it was implemented by the user: br.com.foo.bar .

In PHP I can tell if it was the User who defined the class using the following:

  

$ ReflectionClass = new ReflectionClass ($ class_name);

     

$ ReflectionClass-> isUserDefined ();

Would there be some way for me to achieve this in JAVA without doing a lot of:

method.getReturnType() == String.class || method.getReturnType() == Integer.class
    
asked by anonymous 30.07.2015 / 19:08

2 answers

2
/** Testa se o pacote da classe começa com "java." ou "javax."
  * Talvez seja o caso de também testar os pacotes "org." listados em:
  * http://docs.oracle.com/javase/8/docs/api/overview-summary.html */
private boolean ehClasseDoJava(Class<?> clazz) {
    return clazz.getPackage() != null
        && clazz.getPackage().length() >= 6
        && (clazz.getPackage().substring(0, 5).equals("java.")
            || clazz.getPackage().substring(0, 6).equals("javax."));
}

Use this:

System.out.println(ehClasseDoJava(seuObjeto.getClass())); // imprime true ou false
    
30.07.2015 / 19:43
1

Normally classes loaded by the System ClassLoader (bootstrap) return null when we call your ClassLoader.

public class Main {

  public static void main(String[] args) {
    System.out.println(Main.class.getClassLoader()); //retorna o Classloader
    System.out.println(System.class.getClassLoader()); //retorna null
    System.out.println(Sdp.class.getClassLoader()); //retorna null
    System.out.println(BufferSecrets.class.getClassLoader()); //retorna null
    System.out.println(AbsoluteIterator.class.getClassLoader()); //retorna null
  }

}

This can be an alternative to checking if the class has been loaded by the bootstrap, if it is, then the class is JVM primitive.

    
30.07.2015 / 20:19