Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to check whether a given class type belongs to Java object or custom object

I was searching for any ways to check whether the type of the given attribute of a class is of custom object type (for eg., Person) or Java object (for eg., String, Long, primitive types as well) type. If instanceof is used, it will be hectic checking all of the Java types. Can anyone suggest a way to check, if anything as such exists.

like image 257
Sarath Avatar asked Sep 23 '13 20:09

Sarath


1 Answers

Java is very much "built on itself". Much of the SDK could be considered both "custom" or "built-in" depending on which way you are looking at it.

For instance, Exception is built in to Java but also written in Java. You could write similar code yourself, however based on what you've said I am guessing you would consider it a "Java object".

Similarly, ArrayList is also written in Java, but because it's a utility class, I'm guessing you would consider it "custom", though I'm not sure, since it is still included in the SDK.

Without knowing exactly what you are looking for, the closest grouping that I can guess based on what you've said (String, Long, etc.) is the java.lang package. In the words of the SDK documentation itself, the java.lang package:

Provides classes that are fundamental to the design of the Java programming language.

You can check if the package name of the class for the object is in java.lang:

static class A {
    
}

public static void main (String[] args) {
    String test1 = "";
    A test2 = new A();
    int test3 = 3;

    System.out.println(isJavaLang(test1));
    System.out.println(isJavaLang(test2));
    System.out.println(isJavaLang(test3));
}

public static boolean isJavaLang(Object check) {
    return check.getClass().getName().startsWith("java.lang");
}

Working example

like image 60
Nicole Avatar answered Nov 15 '22 11:11

Nicole