Basics of Java Reflection Constructors - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Basics of Java Reflection Constructors

Share This

To get constructors of a class, you can write a code as follow.

Content of TestMain.java
package com.t4b.test; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class TestMain { public static void main(String[] args) { new DBConnection(); ClassLoader classLoader = DBConnection.class.getClassLoader(); try { Class aClass = classLoader.loadClass("com.t4b.test.DBConnection"); System.out.println("aClass.getName() = " + aClass.getName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } Constructor constructor; try { constructor = DBConnection.class.getConstructor(); DBConnection myObject = (DBConnection) constructor.newInstance(); myObject.dispaly(); System.out.println("#" + myObject.getClass().getName()); } catch (NoSuchMethodException | SecurityException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.