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

Asked

Viewed 349 times

5

I created a method that uses Reflection to run getters on top of an object, but I need to know if the class is native to JAVA, for example: java.lang.String, or whether it has been 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($classname);

$Reflectionclass->isUserDefined();

Would there be some way I could achieve this in JAVA without doing a lot of:

method.getReturnType() == String.class || method.getReturnType() == Integer.class
  • In java you have the getClass() of the object, which will return you the class. To compare you use the method equals() also of the object.

  • @Denie exactly what I don’t want to do, take the class and keep comparing with all the java natives.

  • Ah yes now I understand

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 like this:

System.out.println(ehClasseDoJava(seuObjeto.getClass())); // imprime true ou false
  • Well thought out is how to take the package and see where it comes from. Tomorrow I test if everything went right.

1

Normally classes loaded by the system’s 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 check if the class was loaded by bootstrap, if so, then the class is JVM primitive.

  • It can be a good and also efficient way to discover, but it is necessary to be attentive if the getClassLoader() of the Java implementation used has this return behavior null even, as the documentation of the method warns.

  • In the documentation itself it is clear that there is a possibility of not returning null. !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.