Rule Definition
Dynamic instantiation is slower than a regular Class invocation or Method call
Remediation
You should use class invocation or method call instead of dynamic instantiation
Violation Code Sample
Sample1 package org.hsqldb; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; ... public class HsqlSocketFactory { protected HsqlSocketFactory() throws Exception {} public static HsqlSocketFactory getInstance(boolean tls) throws Exception { return tls ? getSSLImpl() : getPlainImpl(); } ... ---------------------------------------------------------------- Sample2 package com.tutorialspoint; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class MethodDemo { public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { Method[] methods = SampleClass.class.getMethods(); SampleClass sampleObject = new SampleClass(); methods[1].invoke(sampleObject, "data"); System.out.println(methods[0].invoke(sampleObject)); } }
Reference
https://docs.oracle.com/javase/tutorial/reflect/index.html
Related Technologies
JEE
Technical Criterion
Complexity - Dynamic Instantiation
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.