Get int class java

Java Integer getClass()

Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.

The actual result type is Class where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:

Number n = 0;
Class c = n.getClass();

Syntax

The method getClass() from Integer is declared as:

@IntrinsicCandidate public final native Class getClass(); 

The method getClass() returns The Class object that represents the runtime class of this object.

Example

The following code shows how to use Integer from java.lang.

Specifically, the code shows you how to use Java Integer getClass()

/*// w ww . d e m o2 s . c o m * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.util.logging.Level; import java.util.logging.Logger; /** * * @author mandrade */ public class Test < public static void main(String[] args) < Integer object = new Integer(1); Logger.getLogger(Test.class.getName()).log(Level.INFO, "TYPE:", new Object[] < object.getClass().getSimpleName() >); > >
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.Random; public class ProxyTest < public static void main(String[] args) < Object[] elements = new Object[1000]; //Creates an array of objects // fill elements with proxies for the integers 1 . 1000 for (int i = 0; i < elements.length; i++) < Integer value = i + 1; // Class[] interfaces = value.getClass().getInterfaces(); InvocationHandler handler = new TraceHandler(value); Object proxy = Proxy.newProxyInstance(null, interfaces, handler); elements[i] = proxy;/* w w w . de mo 2s . c o m */ > // construct a random integer Integer key = new Random().nextInt(elements.length) + 1; // search for the key int result = Arrays.binarySearch(elements, key); // print match if found if (result >= 0) System.out.println(elements[result]); > > /** An invocation handler that prints out the method name and parameters, then invokes the original method */ class TraceHandler implements InvocationHandler < /** Constructs a TraceHandler @param t the implicit parameter of the method call */ public TraceHandler(Object t) < target = t; >public Object invoke(Object proxy, Method m, Object[] args) throws Throwable < // print implicit argument System.out.print(target); // print method name System.out.print("." + m.getName() + "("); // print explicit arguments if (args != null) < for (int i = 0; i < args.length; i++) < System.out.print(args[i]); if (i < args.length - 1) System.out.print(", "); > > System.out.println(")"); // invoke actual method return m.invoke(target, args); > private Object target; >
import java.lang.reflect.Method; import junit.framework.TestCase; import simkit.util.Misc; /**/*w w w. d em o 2 s . c o m */ * Verify that java reflection works the way we are using it. * * @author Kirk Stork (The MOVES Institute) */ public class JavaReflectionTest extends TestCase < public JavaReflectionTest(String testName) < super(testName); > @Override protected void setUp() throws Exception < super.setUp(); > @Override protected void tearDown() throws Exception < super.tearDown(); > class SomethingToReflectUpon < public void foo(Double x, Integer y) < >public void baz(int x, Integer y) < >public int returnZero() < return 0; > protected void protectedNoOp() < >> public void testGetFullMethodName_Class_String_Array() < Object[] arg = new Object[] < new Double(1.0), new Integer(3) >; Method[] method = SomethingToReflectUpon.class.getDeclaredMethods(); // for (int i = 0; i < method.length; i++) // System.out.println(method[i] + ": " + method[i].getName()); // > // simkit.util.Misc reflects on the given class and produces // a string representation of the method if it exists. Notice, the // arguments must be objects, not primative types String name = Misc.getFullMethodName(SomethingToReflectUpon.class, "foo", arg); // System.out.println(name); assertEquals( "simkit.JavaReflectionTest$SomethingToReflectUpon.foo" + "(java.lang.Double,java.lang.Integer)", name); try < name = Misc.getFullMethodName(SomethingToReflectUpon.class, "bar", arg); // System.out.println(name); fail("should have received an exception"); > catch (RuntimeException e) < assertSame(java.lang.NoSuchMethodException.class, e.getCause().getClass()); > // only for methods that return void . try < name = Misc.getFullMethodName(SomethingToReflectUpon.class, "returnZero", arg); // System.out.println(name); fail("should have received an exception"); > catch (RuntimeException e) < assertSame(java.lang.NoSuchMethodException.class, e.getCause().getClass()); > // and only for methods that are public try < name = Misc.getFullMethodName(SomethingToReflectUpon.class, "protectedNoOp", arg); // System.out.println(name); fail("should have received an exception"); > catch (RuntimeException e) < assertSame(java.lang.NoSuchMethodException.class, e.getCause().getClass()); > > public void testGetFullMethodName_String_Array() < Object[] arg = new Object[] < new Double(1.0), new Integer(3) >; Method[] method = SomethingToReflectUpon.class.getDeclaredMethods(); String name; // There is no bar method anywhere, but simkit.util.Misc can still create // a string representation that includes argumement type information. name = Misc.getFullMethodName("bar", arg); assertEquals("bar(class java.lang.Double,class java.lang.Integer)", name); > public void testsSimpleReflection() < Method[] method = SomethingToReflectUpon.class.getDeclaredMethods(); Class intClass = int.class; int x = 1; Integer y = new Integer(x); assertFalse(intClass.isAssignableFrom(y.getClass())); assertTrue(intClass.isAssignableFrom(Integer.TYPE)); assertTrue(Integer.TYPE.isAssignableFrom(intClass)); System.out.println(); assertEquals(4, method.length); assertEquals("public void simkit.JavaReflectionTest$Something" + "ToReflectUpon.foo(java.lang.Double,java.lang.Integer)", method[0].toString()); assertEquals("foo", method[0].getName()); assertEquals("public void simkit.JavaReflectionTest$Something" + "ToReflectUpon.baz(int,java.lang.Integer)", method[3].toString()); assertEquals("baz", method[3].getName()); assertEquals("public int simkit.JavaReflectionTest$Something" + "ToReflectUpon.returnZero()", method[1].toString()); assertEquals("returnZero", method[1].getName()); assertEquals("protected void simkit.JavaReflectionTest$Something" + "ToReflectUpon.protectedNoOp()", method[2].toString()); assertEquals("protectedNoOp", method[2].getName()); // System.out.println(); // System.out.println(SomethingToReflectUpon.class.getName()); assertEquals("simkit.JavaReflectionTest$SomethingToReflectUpon", SomethingToReflectUpon.class.getName()); > >

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

How to Get Type of Object in Java?

An object is a physical entity that has its own state and behavior, and it acts as a unique instance of a Java class. It. When the object originates from a source, it is considered useful to examine the object type. Also, knowing the type of an object is crucial when working with a collection that includes different objects or when it is required to execute the logical operation with the same kind of variables.

This article will help you to learn the method to get the type of an object in Java.

How to Get Type of Object in Java?

For getting the type of predefined or user-defined class object in Java, you can use:

We will now check out each of the mentioned methods one by one!

Method 1: Get Type of Pre-defined Class Object Using getClass() Method

In Java, we have predefined classes like wrapper classes such as String, Double, Integer, and many more. Sometimes we need to verify the object type while using predefined classes. For this purpose, Java offers a “getClass()” method that belongs to the “Object” class.

Syntax
The syntax of the “getClass()” method is given as follows:

Here, the “getClass()” method will return the class of the specified “x” object.

Example
In this example, we will create a String type object named “x” containing the following value:

Next, we will print a statement using the “System.out.println()” method:

Lastly, we will get the type of the object “x” by calling the “getClass()” method:

The output shows that the created variable belongs to the Java String class:

Let’s see another method to get the object type using the “instanceof” operator.

Method 2: Get Type of Pre-defined Class Object Using “instanceof” Operator

You can also utilize the “instanceof” operator to check the object type in a Java program. This operator returns a boolean value which indicates whether the object is an instance of the particular class or not.

Syntax
The syntax of the “instanceof” is as follows:

Here, “x” is an object and “Integer” is the predefined Java wrapper class. The “instanceof” operator checks whether the object belongs to the mentioned class or not and returns a boolean value.

Example
In this example, we have an object “x” of the Integer class having “5” as its value:

Next, we will print a statement using the “System.out.println()” method:

Now, we will check whether the object is an instance of an Integer class or not:

The output displayed “true” as the object “x” is an instance of the Integer class:

At this point, you may be wondering about how to get the type of user-defined class object. The below-given section will assist you in this regard.

Method 3: Get Type of User-defined Class Object Using getClass() Method

You can also get the type of the user-defined class object with the help of the “getClass()” method. In such a scenario, we will compare the object with the class name using the “==” comparison operator.

Syntax
For the specified purpose, the syntax of “getClass()” method is given as:

Here, the “getClass()” method is called by the “myclassObj” object of the “MyClass” and then compared with the name using the comparison operator “==”.

Example
In this example, we have three classes named “MyClass”, “MynewClass”, and “Example”, where MyClass acts as a parent class of MynewClass:

The “MynewClass” is a child class as it is extended from “MyClass”:

In the main() method of the class “Example”, we will declare and instantiate an object of the parent class “MyClass”. Then check whether the created object belongs to which class; parent or child? To do so, we will call the “getClass()” method with the created object and compare the resultant value with parent and child class names using if-else-if conditions:

public class Example {
public static void main ( String [ ] args ) {
MyClass myclassObj = new MyClass ( ) ;
if ( myclassObj. getClass ( ) == MyClass. class ) {
System . out . println ( «The object ‘myclassObj’ is a type of ‘MyClass'» ) ;
} else if ( myclassObj. getClass ( ) == MynewClass. class ) {
System . out . println ( «The object ‘myclassObj’ is a type of ‘MynewClass'» ) ;
}
}
}

The output indicates that the object “myclassObj” belongs to the parent class named “MyClass”:

Now, head toward the next section!

Method 4: Get Type of User-defined Class Object Using “instanceof” Operator

Similar to predefined classes, for user-defined classes, you can also get the type of object by using the “instanceof” operator.

Syntax
The syntax is given below:

Here, the “instanceof” operator will check if the “myclassObj” is an instance of “MyClass” or not.

Example
We will now utilize the same classes which we have created in the previously mentioned example. The only difference is that we will use the “instanceof” operator to verify if the created object instance belongs to the parent or child class:

public class Example {
public static void main ( String [ ] args ) {
MyClass myclassObj = new MyClass ( ) ;
if ( myclassObj instanceof MyClass ) {
System . out . println ( «The object ‘myclassObj’ is an instance of ‘MyClass'» ) ;
} else if ( myclassObj instanceof MynewClass ) {
System . out . println ( «The object ‘myclassObj’ is an instance of ‘MynewClass'» ) ;
}
}
}

The given output shows that the “instanceof” operator validated the type of the object as “MyClass”:

We have compiled all methods related to getting object type in Java.

Conclusion

To get a type of object in Java, you can use the “getClass()” method or the “instanceof” operator. These methods can be used to check object types for both predefined and user-defined classes. The getClass() method returns the class name while the “instanceof” operator returns a boolean value, where “true” indicates the object belongs to that specified class; otherwise, it returns “false”. This article provided all the methods to get the object type in Java.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Читайте также:  Codepoint java что это
Оцените статью