Ambert Lency

Ambert Lency

1565942987

Java Reflection API Tutorial

What is Reflection in Java?

Java Reflection is the process of analyzing and modifying all the capabilities of a class at runtime. Reflection API in Java is used to manipulate class and its members which include fields, methods, constructor, etc. at runtime.

One advantage of reflection API in Java is, it can manipulate private members of the class too.

The java.lang.reflect package provides many classes to implement reflection java.Methods of the java.lang.Class class is used to gather the complete metadata of a particular class.

Class in java.lang.reflect Package

Following is a list of various Java classes in java.lang.package to implement reflection-

Field: This class is used to gather declarative information such as datatype, access modifier, name and value of a variable.

Method: This class is used to gather declarative information such as access modifier, return type, name, parameter types and exception type of a method.

Constructor: This class is used to gather declarative information such as access modifier, name and parameter types of a constructor.

Modifier: This class is used to gather information about a particular access modifier.

Methods used in java.lang.Class

Public String getName (): Returns the name of the class.

Public Class getSuperclass(): Returns the super class reference

Public Class[] getInterfaces() : Returns an array of interfaces implemented by the specified class

Public in getModifiers (): Returns an integer value representing the modifiers of the specified class which needs to be passed as a parameter to "public static String toString (int i )" method which returns the access specifier for the given class.

How to get complete information about a class

To get information about variables, methods, and constructors of a class, we need to create an object of the class.

public class Guru99ClassObjectCreation {
	public static void main (String[] args) throws ClassNotFoundException {
		//1 - By using Class.forname() method 
		Class c1 = Class.forName("Guru99ClassObjectCreation"); 
		//2- By using getClass() method 
		Guru99ClassObjectCreation guru99Obj = new Guru99ClassObjectCreation();
		Class c2 = guru99Obj.getClass();
		//3- By using .class 
		Class c3= Guru99ClassObjectCreation.class;
		}
	}

Following example shows different ways to create object of class "class" :

Example 1 : How to get Metadata of Class

Following example shows how to get metadata such as: Class name, super class name, implemented interfaces, and access modifiers of a class.

We will get the metadata of below class named Guru99Base.class:

import java.io.Serializable;
public abstract class Guru99Base implements Serializable,Cloneable {
}
  1. Name of the class is: Guru99Base
  2. It's access modifiers are: public and abstract
  3. It has implemented interfaces: Serializable and Cloneable
  4. Since it has not extended any class explicitly, it's super class is: java.lang.Object

Below class will get the meta data of Guru99Base.class and print it:

import java.lang.reflect.Modifier;
public class Guru99GetclassMetaData {
public static void main (String [] args) throws ClassNotFoundException { 
// Create Class object for Guru99Base.class 
Class guru99ClassObj = Guru99Base.class;

// Print name of the class 
system.out.println("Name of the class is : " +guru99ClassObj.getName());

// Print Super class name
system.out.println("Name of the super class is : " +guru99ClassObj.getSuperclass().getName());

// Get the list of implemented interfaces in the form of Class array using getInterface() method
class[] guru99InterfaceList = guru99classObj.getInterfaces();

// Print the implemented interfaces using foreach loop 
system.out.print("Implemented interfaces are : ");
for (Class guru99class1 : quru99 InterfaceList)	{
	system.out.print guru99class1.getName() + " ");
}
system.out.println();

//Get access modifiers using get Modifiers() method and toString() method of java.lang.reflect.Modifier class
int guru99AccessModifier= guru99classObj.getModifiers(); 
// Print the access modifiers
System.Out.println("Access modifiers of the class are : " +Modifier.tostring(guru99AccessModifier));

}

}

  1. print the name of the class using getName method
  2. Print the name of the super class using getSuperClass().getName() method
  3. Print the name of the implemented interfaces
  4. Print the access modifiers used by the class

Example 2 : How to get Metadata of Variable

Following examples shows how to get metadata of variable:

Here, we are creating a class named Guru99VariableMetaData .class with some variables:

package guru;
public class Guru99VariableMetaData {
public static int guru99IntVar1=1111;
static int guru99IntVar2=2222;
static String guru99StringVar1=“guru99.com”;
static String guru99StringVar2=“Learning Reflection API”;
}

Steps to get the metadata about the variables in the above class:

Create the class object of the above class i.e. Guru99VariableMetaData.class as below:

  Guru99VariableMetaData  guru99ClassVar  = new Guru99VariableMetaData();
Class guru99ClassObjVar = guru99ClassVar.getClass();

Get the metadata in the form of field array using getFields() or getDeclaredFields() methods as below:

Field[]  guru99Field1= guru99ClassObjVar .getFields();
Field[] guru99Fiel2= guru99ClassObjVar .getDeclaredFields();

getFields() method returns metadata of the public variable from the specified class as well as from its super class.

getDeclaredFields() method returns metadata of the all the variables from the specified class only.

  1. Get the name of the variables using “public String getName()” method.
  2. Get the datatype of the variables using “public Class getType()” method.
  3. Get the value of the variable using “public xxx get (Field)” method.
  4. Here, xxx could be a byte or short of any type of value we want to fetch.
  5. Get the access modifiers of the variables using getModifier() and Modifier.toString(int i) methods.
  6. Here, we are writing a class to get the metadata of the variables present in the class Guru99VariableMetaData .class:
package guru;
import java.lang.reflect.Field;

public class Guru99VariableMetaDataTest {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
// Create Class object for Guru99VariableMetaData.class
Guru99VariableMetaData guru99ClassVar = new Guru99VariableMetaData();
Class guru99ClassObjVar = guru99ClassVar.getClass();

// Get the metadata of all the fields of the class Guru99VariableMetaData 
Field[] guru99Field1= guru99ClassObjVar.getDeclaredFields();

// Print name, datatypes, access modifiers and values of the varibales of the specified class 
for(Field field : guru99Field1) { 
System.out.println("Variable name : "+field.getName());
System.out.println("Datatypes of the variable :"+field.getType());

int guru99AccessModifiers = field.getModifiers();
System.out.printlln("Access Modifiers of the variable : "+Modifier.toString(guru99AccessModifiers));
System.out.println("Value of the variable : "+field.get(field));
System.out.println();
system.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *") ;
}
}

}

  1. Created class object for Guru99VariableMetaData.class
  2. Got all the metadata of the variables in a Field array
  3. Printed all the variable names in the class Guru99VariableMetaData.class
  4. Printed all the data types of the variables in the class Guru99VariableMetaData.class
  5. Printed all the access modifiers of the variables in the class Guru99VariableMetaData.class
  6. Printed values of all the variables in Printed all the data types of the variables in the class Guru99VariableMetaData.class

Example 3 : How to get Metadata of Method

  1. Following examples shows how to get metadata of a method:
  2. Here, we are creating a class named Guru99MethodMetaData .class with some methods
package guru;		
import java.sql.SQLException;
public class Guru99MethodMetaData {

public void guru99Add(int firstElement, int secondElement , String result) 									
throws ClassNotFoundException, ClassCastException{			
      System.out.println("Demo method for Reflextion  API");					
}	
public String guru99Search(String searchString) 			
throws ArithmeticException, InterruptedException{			
    System.out.println("Demo method for Reflection API");					
	return null;					
}	
public void guru99Delete(String deleteString) 					
throws SQLException{			
    System.out.println("Demo method for Reflection API");					
}	

}

Steps to get the metadata about the methods in the above class :

Create the class object of the above class i.e. Guru99MethodMetaData.class as below:

Guru99MethodMetaData  guru99ClassVar  = new Guru99MethodMetaData  ();
Class guru99ClassObjVar = guru99ClassVar.getClass();

Get method information in a Method array using getMethods() and getDeclaredMethods() method as below:

Method[]  guru99 Method 1= guru99ClassObjVar .get Methods();
Method [] guru99 Method 2= guru99ClassObjVar .getDeclared Method s();

getMethods() method returns metadata of the public methods from the specified class as well as from its super class.

getDeclaredMethods() method returns metadata of the all the methods from the specified class only.

Get the name of the method using getName() method.

Get the return type of the method using getReturnType() method.

Get access modifiers of the methods using getModifiers() and Modifiers.toString(int i) methods.

Get method parameter types using getParameterTypes() method which returns a class array.

Get thrown exception using getExceptionTypes() method which returns a class array.

Here, we are writing a class to get the metadata of the methods present in the class Guru99MethodMetaData.class:

package guru;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Guru99MethodMetaDataTest {

public static void main (String[] args) {
	// Create Class object for Guru99Method MetaData.class 
	class guru99ClassObj = Guru99MethodMetaData.class;

	// Get the metadata or information of all the methods of the class using getDeclaredMethods() 
	Method[] guru99Methods=guru99classObj.getDeclaredMethods();

	for(Method method : guru99Methods) { 
	// Print the method names
	System.out.println("Name of the method : "+method.getName());
	
	// Print return type of the methods 
	System.out.println("Return type of the method : "+method.getReturnType());
	
	//Get the access modifier list and print
	int guru99ModifierList = method.getModifiers(); 
	System.Out.printlin ("Method access modifiers : "+Modifier.toString(guru99ModifierList));
	
	// Get and print parameters of the methods 
	Class[] guru99ParamList= method.getParameterTypes(); 
	system.out.print ("Method parameter types : "); 
	for (Class class1 : guru99ParamList){ 
		System.out.println(class1.getName()+" ");
	}
    System.out.println();
	
	// Get and print exception thrown by the method 
	Class[] guru99ExceptionList = method. getExceptionTypes(); 
	system.out.print("Excpetion thrown by method :"); 
	for (Class class1 : guru99ExceptionList) {
		System.out.println (class1.getName() +" "):
	} 
	System.Out.println(); 
	system.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ");
	
	}

}

}

Created class object for Guru99MethodMetaData.class

Got all the metadata of all the methods in a Method array

Printed all the method names present in the class Guru99MethodMetaData.class

Printed return types of the methods in the class Guru99MethodMetaData.class

Printed all the access modifiers of the methods in the class Guru99MethodMetaData.class

Printed parameter types of the methods in Guru99MethodMetaData.class

Printed exceptions are thrown by methods in Guru99MethodMetaData.class

Example 4 : How to get Metadata of Constructors

  1. Following examples shows how to get metadata of constructors:
  2. Here, we are creating a class named Guru99Constructor.class with different constructors:
package guru;

import java.rmi.RemoteException;
import java.sql.SQLException;

public class Guru99Constructor {

public Guru99Constructor(int no) throws ClassCastException ,ArithmeticException{  }							
public Guru99Constructor(int no, String name) throws RemoteException ,SQLException{  }							
public Guru99Constructor(int no, String name, String address) throws InterruptedException{  }							

}

Here, we are writing a class to get the metadata of the constructors present in the class Guru99Constructor.class:

package guru;
import java.lang.reflect.Constructor;
public class Guru99ConstructorMetaDataTest {

public static void main (String[] args) {
	// Create Class object for Guru99Constructor.class 
	Class guru99Class=Guru99Constructor.class;

	// Get all the constructor information in the Constructor array
	Constructor[] guru99ConstructorList = guru99Class.getConstructors();
	
	for (Constructor constructor : guru99ConstructorList) {
		// Print all name of each constructor
		System.out.println("Constrcutor name : "+constructor.getName());
		
		//Get and print access modifiers of each constructor 
		int guru99Modifiers= constructor.getModifiers(); 
		System.Out.printlin ("Constrctor modifier : "+Modifier.toString(guru99Modifiers));
		
		// Get and print parameter types 
		Class[] guru99ParamList=constructor.getParameterTypes();
		System.out.print ("Constrctor parameter types :"); 
		for (Class class1 : guru99ParamList) { 
			System.out.println(class1.getName() +" ");
		}
		System. out.println();

		// Get and print exception thrown by constructors
		Class[] guru99ExceptionList=constructor.getFxceptionTypes();
		System.out.println("Exception thrown by constructors :"); 
		for (Class class1 : guru99ExceptionList) { 
			System.out.println(class1.getName() +" ");
		} 
		System.out.println();
		System.out.println("*******************************************");
	}
}

}

  1. Created class object for Guru99Constructor.class
  2. Got all the metadata of all the constructors in a Constructor array
  3. Printed all the constructor’s names present in the class Guru99Constructor.class
  4. Printed all the access modifiers of the constructors in the class Guru99Constructor.class
  5. Printed parameter types of the constructors in Guru99Constructor.class
  6. Printed exceptions are thrown by constructors in Guru99Constructor.class

Summary:

  • Reflection programming in java helps in retrieving and modifying information about Classes and Class members such variable, methods, constructors.
  • Reflection API in Java can be implemented using classes in java.lang.reflect package and methods of java.lang.Class class.
  • Some commonly used methods of java.lang.Class class are getName (), getSuperclass (), getInterfaces (), getModifiers () etc.
  • Some commonly used classes in java.lang.reflect package are Field, Method, Constructor, Modifier, etc.
  • Reflection API can access private methods and variables of a class which could be a security threat.
  • Reflection API is a powerful capability provided by Java, but it comes with some overheads such as slower performance, security vulnerability, and permission issue. Hence, reflection API should be treated as the last resort to performing an operation.


Thanks for reading. If you liked this post, share it with all of your programming buddies!

Originally published on guru99.com

#java #api #web-development

What is GEEK

Buddha Community

Java Reflection API Tutorial
Samanta  Moore

Samanta Moore

1621111320

How to Validate an Email Address in Java

Email is one of the most universal tools for sharing and receiving information across the globe, with users able to connect with others online with almost no compatibility or access issues. Using this tool, information can be instantly and securely sent to partners on the other side of the world, and personal information can be verified without divulging sensitive data about a user.

Along with this widespread use, however, comes key security measures that must take place in order to ensure the safety of your organization and data. This is particularly the case when receiving email information from previously unknown sources. These risks can include phishing attempts, malware, and other threats that can cause a negative impact to your business. Furthermore, when receiving an email address via account forms and user sign up information, you need to check that the information you are given is not only correct and real, but also that it does not lead to any malicious sources that could harm your organizational security.

The following APIs will allow you to instantly verify and validate an input email address without sending any kind of notification to the email user. This will help protect your organization in the event of any threats. The goal of this tutorial is to provide you with the tools to protect your organization’s information while providing a way to verify new accounts and user information.

This will be done through three separate functions. The first will analyze the validity of an email address’ syntax. The second will check for the address’ servers, and the third performs a full email address validation including returning the results for the previous two functions.

#java #api #java api #api access keys #api tutorial #email verification #email validation #java api tutorials #java apis #api tutorials

Samanta  Moore

Samanta Moore

1621118940

How to Convert ODT Files to PDF in Java

Convert Office Open Document Text File (ODT) to standard PDF, DOCX, PNG, and JPG using Java.

Microsoft has maintained its position in the spotlight for formatted document creation and editing for good reason. Its extreme ease of use and lack of a learning curve has transformed the Microsoft Office Suite into a household name for most computer users in the United States as well as globally. This is propagated further through its almost ubiquitous use in education, as students are raised and taught using these applications.

The issue that arises with these programs, however, is their operation costs. For Apple and other non-Windows-based Operating Systems, the purchasing fees for Office can be steep. This, then, creates a paywall separating potential users from programs to which they are already accustomed. As an answer this problem, Microsoft created the OpenOffice application, which is a free, opensource version of the classic Office Suite. Within this application, you can perform almost all of the same functions as Office Suite, including creating text documents like one would with Microsoft Word. These text documents can be made using OpenOffice Writer, and are formatted using the .ODT file type. While this file type can be opened and saved using OpenOffice Writer and Word, in order to convert the file to a different format such as PDF you will need to run it through a conversion process.

The following APIs will allow you to convert your ODT documents to PDF, DOCX, PNG, and JPG for use in whatever way you need. The goal of this tutorial is to provide a simple and efficient means for instantly converting your ODT files without needing to find or download any extraneous programming.

#java #tutorial #api #pdf #java api #pdf converter #api access keys #api tutorial #java api tutorials #java apis

Samanta  Moore

Samanta Moore

1621269360

How to Create a Barcode Image in Java

The following five APIs will allow you to create barcode images in the three previously mentioned formats.

Barcodes are used universally in commerce and retail to aid in tracking, purchasing, and inventory. This allows organizations to keep accurate records of their supplies, products, and other items that are pivotal to their operations. For international and national use, there are different barcodes that are utilized for specific contexts. For example, UPC and EAN barcodes look similar in their formatting and can be used in similar ways, but UPC is a largely North American coding system; however, both UPC and EAN are used globally. QR Codes are also used globally but are usually employed for sharing complex sets of information like item details or website links.

The following five APIs will allow you to create barcode images in the three previously mentioned formats. This will allow you to print or create packaging with your personal barcodes attached, without needing to retrieve it from an outside source. This can be especially useful for small businesses as it provides increased independence as a company and improved visual, professional appeal for your products.

#java #tutorial #api #java api #qr code #api access keys #java api tutorials #barcode generator #api tutorials #barcode api

Ray  Patel

Ray Patel

1623377040

How to Validate and Geocode a Street Address in Java

When working with location services, it is important that the information you collect is accurate for your users or clients. Find out more!

When working with location services, it is important that the information you collect is accurate for your users or clients. This will prevent any mistakes in shipping, billing, and many other aspects of operations that rely on correct location information. For businesses that have applications using location services, this is especially important as any incorrect data can mean the displacement of goods or interrupted services.

The following APIs will allow you to fully validate street addresses by first parsing address data input and then verifying and normalizing the information. The last two APIs will also allow you to geocode and reverse geocode an address to receive more accurate location data for your applications.

#tutorial #api #address #java api #validation and verification #api access keys #api tutorial #validate #java api tutorials #api tutorials

Tyrique  Littel

Tyrique Littel

1600135200

How to Install OpenJDK 11 on CentOS 8

What is OpenJDK?

OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE). It contains the virtual machine, the Java Class Library, and the Java compiler. The difference between the Oracle OpenJDK and Oracle JDK is that OpenJDK is a source code reference point for the open-source model. Simultaneously, the Oracle JDK is a continuation or advanced model of the OpenJDK, which is not open source and requires a license to use.

In this article, we will be installing OpenJDK on Centos 8.

#tutorials #alternatives #centos #centos 8 #configuration #dnf #frameworks #java #java development kit #java ee #java environment variables #java framework #java jdk #java jre #java platform #java sdk #java se #jdk #jre #open java development kit #open source #openjdk #openjdk 11 #openjdk 8 #openjdk runtime environment