BM Balmiki Mandal 06 May 2023 9 views 0 comments Core Java

Java, Class Type, String, Class.forName(), Objects

Getting Class Type From a String in Java

In Java, it is sometimes necessary to know the class type of an object from a string representation. This can be done through the use of the Class.forName() method. This method takes a fully qualified name of a class as the argument and returns a Class object that represents that class.

The fully qualified name of a class includes both its package name and its class name. For example, if the class MyClass is located in the package com.example, then its fully qualified name would be com.example.MyClass. With this information, it is then possible to get the Class object for this class using the Class.forName() method.

Here is an example of how to use the Class.forName() method to get the Class object for a given fully qualified class name:

String className = "com.example.MyClass";
Class<?> clazz = Class.forName(className);
System.out.println("Class Type = " + clazz.getName());
// output: Class Type = com.example.MyClass

Once you have the Class object, you can then check its type with the instanceof operator or query its methods, fields, and annotations. It is also possible to create new instances of the class by calling the newInstance() method on the Class object.

In summary, the Class.forName() method is a useful utility for getting the Class type from a fully qualified class name string.

Share:

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Unlock the Ins and Outs of JavaScript Engines and Runtimes

What is a JavaScript Engine? A JavaScript engine is a program or interpreter which executes JavaScript code....

BM Balmiki Mandal 05 Sep 2023
Implementing HMACSHA256 Algorithm in Java with Key

Introducing HMACSHA256 in Java with Key HMACSHA256 is an authentication algorithm designed to secure data, su...

BM Balmiki Mandal 30 Aug 2023
HMACSHA256 Java Example - Creating Secure Message Authentication

HMACSHA256 Java Example HMACSHA256 is an advanced encryption algorithm that allows developers to create encry...

BM Balmiki Mandal 30 Aug 2023