ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java Examples - Various Ways to Find Instance Type Through Reflection

Updated on July 29, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like playing video games & reading books.

1. Introduction to Java Reflection

Reflection in Java is an approach of RTTI (Run Time Type Identification) in terms of C++ language. In addition, Java allows invoking the type members as well. For example, once we find the type as Runtime we can also its members.

One may think how we do not know a type at compile time. But in reality when we write code there is a significant circumstance where we may not know the type of the instance. The Polymorphism is one good example in which we may not know the type of the instance at compile time. Through RTTI technique, it can be identified at Runtime on the fly. Reflection in Java helps in designing robust and configuration application.

In this example, we will create two classes and one Interface. Then we will get its name at Runtime.

2. What is class, Class and Instance?

A class in Java is a template definition of an object. Based on the class template one can create one or more objects from it. We call these objects as Instances.

A Class (Note the capital C) in Java is template definition that defines objects types. Application developers cannot create an instance from it. However, Java will create the instances of it when an object of any type is loaded at run-time. For Example, when Java application creates a class instance called SecurityFile, then Java creates a class instance of Class to denote its type.

From the instance of a class Class, we can retrieve run-time information of the class type. For each type, Java can load only one Class instance in memory and we can retrieve the RTTI from it. For Example, even if user created ten instances of SecurityFile objects, Java creates only one instance of the Class for the class type SecurityFile. This one instance is enough to get the type information about the object SecurityFile object.

OK. Let us start our example and learn further while we proceed.

3. The IOrg interface

A Class instance in Java can represent an Array, Enumeration, Interface, class instances etcetera. Now, we will create an Interface of type IOrg. Below is the code that defines the IOrg interface:

//Sample01: Define IOrg Interface
public interface IOrg
{
    public int getTotalIncome();
    public int getTotalExpense();
}

4. The Org class

Now, we define a class template called Organization. It has two private and two public data members. Besides, we keep two public functions in the class. Moreover, this class implements the IOrg interface which we defined in the previous section. The class template definition for the Organization is shown below:

//Sample 02: Define Organization class
public class Organization implements IOrg
{
    private int Total_Income;
    private int Total_Expense;
    public int Total_Employee;
    public String Org_Name;

    public int getTotalIncome()
    {
        return Total_Income;
    }

    public int getTotalExpense() {
        return Total_Expense;
    }
}

5. The Department Class

After we define the Organization, we inherit the Department from it. This is not a right design as Department is not an organization. At the same time, an organization may contain one or more departments. We inherited the Department from Organization just to explore the Java reflection. This class contains two public members. The class definition is below:

//Sample 03: Define Department class
public class Department extends Organization
{
    public int DeptID;
    public String Location;
}

So, for we defined the types IOrg, Organization and Department. We also established a relationship between them. Now let us see, how we can retrieve the types at run-time using Java Reflection. The relatioship between the types are shown in the below depiction:

Java Reflection - Types Relation
Java Reflection - Types Relation | Source

6. Accessing Types Dynamically

We can get java types at runtime using three types techniques offered by the Java Reflection. These methods are listed below:

  1. <TypeName>.class technique
  2. Class.forName() technique
  3. <objectRef>.getClass() technique

We will explore each option with an example by making use of types we created in the earlier sections.

When we want to write a generic function for dealing with RTTI, we may end-up in creating the parameters. Parameters require well-defined types and how do we pass Class types which is not known? We must use the Class <?> syntax for denoting such a parameter. For example, look at the code snippet below:

//Sample04: Get Class Name
public static void PrintClassInfo(Class<?> ClassName)
{
	System.out.println(ClassName.getSimpleName());
}

Here, when defining the function, we kept the Generic form of the Class instance by using the Class<?> form. Next, we make a call to the getSimpleName method to print the Type passed to the PrintClassInfo function.

6.1 Reflection by .class

When we know the Class Type and object reference is not yet available, we can use the TypeName.class syntax to retrieve the Class from the class type. Have a look at the below code snippet:

//Sample05: Get the Name from Types
System.out.println("Print Class Name from Type");
PrintClassInfo(Organization.class);
PrintClassInfo(IOrg.class);
PrintClassInfo(Department.class);

Here, we use the <TypeName.class> syntax to retrieve the Class skeleton of Organization, IOrg and Department. Then, it is passed to the PrintClassInfo function which we defined in the previous section. This technique is useful to get Class template of primitive types as well.

6.2 Reflection by .getClass

We can call getClass method when the object reference is available in the caller context. The call will return the Class template instance to the caller for performing any RTTI operation. Now, look at the code snippet given below:

//Sample06: Let us Get the Name from Object
System.out.println("Print Class Name from Object");
Organization org = new Organization();
Department dept = new Department();
Organization Org1 = new Department();
PrintClassInfo(org.getClass());
PrintClassInfo(dept.getClass());
PrintClassInfo(Org1.getClass());

In the above code, have a glance at the code snippet’s line number 3 and 5. Now, in line 3, we are constructing the Organization object and pointing that through the reference Org of a class type Organization. Then we are creating the Department object in like manner and in place of referencing it through the Department reference; we point it through the Organization reference named Org1. The below depiction shows the reference and physical class instance it points:

Reference Type and Object Type
Reference Type and Object Type | Source

In the above picture, the Organization reference Org points to Organization object. This is a straightforward case as the reference and actual object belongs to the same type. Besides, the reference Org1 of type Organization is pointing to a Department instance. The Object Oriented Languages allows this given that there is a valid relation between the objects. In our example, the Department class is inherited from the Organization class. In addition, the Organization is the base class for the Department and as a result a base class reference Org1 can point to a derived class instance of type Department.

The Java Reflection, correctly identifies the class type as department even though we pass Org1 of type Organization to the PrintClassInfo function. This because the actual object pointed by Org1 reference is a Department object.

6.3 class.forName

Java Reflection can get Class of a class instance from a fully qualified class name and forName() method. For example, if we want to retrieve Class template instance of a class Math, we need fully qualified name java.lang.Math not just Math. Now, look at the example below:

//Sample07: From forName
System.out.println("Print Class Name from Fully" +
        "Qualified Name");
try
{
    PrintClassInfo(Class.forName("Organization"));
} catch(Exception Ex)
{
    System.out.println(Ex.toString());
}

In our example, since Organization class is part of the default package, we specify none of the package specification in the class name. Hence, we supply the Organization class name as a string. Also note we formed the class string with no package specification dots. We use the try...catch block to safe guard the call to forName as it may go wrong.

7. Complete Code Example

IOrg.java

//Sample01: Define IOrg Interface
public interface IOrg
{
    public int getTotalIncome();
    public int getTotalExpense();
}

Organization.java

//Sample 02: Define Organization class
public class Organization implements IOrg
{
    private int Total_Income;
    private int Total_Expense;
    public int Total_Employee;
    public String Org_Name;

    public int getTotalIncome()
    {
        return Total_Income;
    }

    public int getTotalExpense() {
        return Total_Expense;
    }
}

Department.java

//Sample 03: Define Department class
public class Department extends Organization
{
    public int DeptID;
    public String Location;
}

Main.java

public class Main
{
    //Sample04: Get Class Name
    public static void PrintClassInfo(Class<?> ClassName)
    {
        System.out.println(ClassName.getSimpleName());
    }

    public static void main(String[] args)
    {
        //Sample05: Get the Name from Types
        System.out.println("Print Class Name from Type");
        PrintClassInfo(Organization.class);
        PrintClassInfo(IOrg.class);
        PrintClassInfo(Department.class);

        //Sample06: Let us Get the Name from Object
        System.out.println("Print Class Name from Object");
        Organization org = new Organization();
        Department dept = new Department();
        Organization Org1 = new Department();
        PrintClassInfo(org.getClass());
        PrintClassInfo(dept.getClass());
        PrintClassInfo(Org1.getClass());

        //Sample07: From forName
        System.out.println("Print Class Name from Fully" +
                "Qualified Name");
        try
        {
            PrintClassInfo(Class.forName("Organization"));
        } catch(Exception Ex)
        {
            System.out.println(Ex.toString());
        }
    }
}

© 2018 sirama

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)