www.techrepublic.com
Open in
urlscan Pro
151.101.66.132
Public Scan
URL:
https://www.techrepublic.com/article/create-wrapper-classes-on-the-fly-with-java-dynamic-proxies/
Submission: On January 13 via manual from US — Scanned from DE
Submission: On January 13 via manual from US — Scanned from DE
Form analysis
4 forms found in the DOM/search/
<form action="/search/" class="search-bar">
<label id="label-nav-site-search" for="nav-site-search"> Search </label>
<input type="search" autocomplete="off" name="q" id="nav-site-search" value="" placeholder="What are you looking for?" required="">
<button type="submit" disabled="disabled">
<svg role="img" aria-labelledby="label-nav-site-search">
<use href="#smart-search-icon"></use>
</svg>
</button>
<input type="hidden" name="o" value="1"><!-- Default to search by relevance -->
</form>
POST
<form class="share-email-form" method="post">
<input type="hidden" name="share-email-title" value="Create wrapper classes on the fly with Java dynamic proxies">
<input type="hidden" name="share-email-url" value="https://www.techrepublic.com/article/create-wrapper-classes-on-the-fly-with-java-dynamic-proxies/">
<input type="email" name="from-email" class="read-write" placeholder="Your Email" required="">
<input type="email" name="to-email" class="read-write" placeholder="Recipient Email" required="">
<textarea name="msg" class="readonly">Check out this article I found on TechRepublic.</textarea>
<input type="submit" value="Submit">
<p class="response-msg">Your email has been sent</p>
</form>
POST
<form class="share-email-form" method="post">
<input type="hidden" name="share-email-title" value="Create wrapper classes on the fly with Java dynamic proxies">
<input type="hidden" name="share-email-url" value="https://www.techrepublic.com/article/create-wrapper-classes-on-the-fly-with-java-dynamic-proxies/">
<input type="email" name="from-email" class="read-write" placeholder="Your Email" required="">
<input type="email" name="to-email" class="read-write" placeholder="Recipient Email" required="">
<textarea name="msg" class="readonly">Check out this article I found on TechRepublic.</textarea>
<input type="submit" value="Submit">
<p class="response-msg">Your email has been sent</p>
</form>
POST
<form class="email-author-form" method="post">
<input type="hidden" name="author_id" value="29505367">
<input type="text" name="from-name" class="read-write" placeholder="Your Name" required="">
<input type="email" name="from-email" class="read-write" placeholder="Your Email" required="">
<input type="text" name="subject" class="read-write" placeholder="Subject" required="">
<textarea name="msg" placeholder="Message" required="" class="read-write"></textarea>
<input type="submit" value="Send Message">
<p class="response-msg">Your message has been sent</p>
</form>
Text Content
WE VALUE YOUR PRIVACY We and our partners store and/or access information on a device, such as cookies and process personal data, such as unique identifiers and standard information sent by a device for personalised ads and content, ad and content measurement, and audience insights, as well as to develop and improve products. With your permission we and our partners may use precise geolocation data and identification through device scanning. You may click to consent to our and our partners’ processing as described above. Alternatively you may access more detailed information and change your preferences before consenting or to refuse consenting. Please note that some processing of your personal data may not require your consent, but you have a right to object to such processing. Your preferences will apply to this website only. You can change your preferences at any time by returning to this site or visit our privacy policy. MORE OPTIONSAGREE Skip to content TECHREPUBLIC Search Close Search * Top Products Lists * Developer * 5G * Security * Cloud * Artificial Intelligence * Tech & Work * Mobility * Big Data * Innovation * Cheat Sheets * TechRepublic Academy * CES Toggle TechRepublic mobile menu More * TechRepublic Premium * Top Products Lists * Developer * 5G * Security * Cloud * Artificial Intelligence * Tech & Work * Mobility * Big Data * Innovation * Cheat Sheets * TechRepublic Academy * CES * See All Topics * Sponsored * Newsletters * Forums * Resource Library TechRepublic Premium Join / Sign In ACCOUNT INFORMATION TechRepublic close modal Dynamic proxies allow Java coders to create wrappers on the fly to prevent malfunctions and save tedious code repetition. Find out what these coding shortcuts are capable of and learn how you can use them in your own applications. CREATE WRAPPER CLASSES ON THE FLY WITH JAVA DYNAMIC PROXIES * * * * ACCOUNT INFORMATION TechRepublic close modal SHARE WITH YOUR FRIENDS Create wrapper classes on the fly with Java dynamic proxies Check out this article I found on TechRepublic. Your email has been sent by ryanbrase in Innovation on June 23, 2003, 12:00 AM PDT CREATE WRAPPER CLASSES ON THE FLY WITH JAVA DYNAMIC PROXIES Dynamic proxies allow Java coders to create wrappers on the fly to prevent malfunctions and save tedious code repetition. Find out what these coding shortcuts are capable of and learn how you can use them in your own applications. The Java 1.3 release introduced a new feature called dynamic proxy classes, which provide a mechanism for creating wrapper classes on the fly for implementations of known interfaces. When I read about the proposed dynamic proxy classes before the 1.3 release, they struck me as a “gee whiz” feature. I was glad they were being included in the language, but I couldn’t think of a single real use for them in systems I’d previously designed. But when I wrote a sample program using dynamic proxies to try them out, I was impressed with their power and stowed them in my toolbox for use on future projects. Since then, I’ve found instance after instance where they provided just the right way to do what needed to be done. Without dynamic proxies Before we look at what dynamic proxy classes are, let’s examine how certain situations were handled before dynamic proxies were introduced. public interface Robot { void moveTo(int x, int y); void workOn(Project p, Tool t); } public class MyRobot implements Robot { public void moveTo(int x, int y) { // stuff happens here } public void workOn(Project p, Tool t) { // optionally destructive stuff happens here } } The above code listing shows an interface named Robot and a roughed-in implementation of that interface named MyRobot. Imagine now that you want to intercept method calls made to the MyRobot class—perhaps limiting the value of a single parameter. public class BuilderRobot implements Robot { private Robot wrapped; public BuilderRobot(Robot r) { wrapped = r; } public void moveTo(int x, int y) { wrapped.moveTo(x, y); } public void workOn(Project p, Tool t) { if (t.isDestructive()) { t = Tool.RATCHET; } wrapped.workOn(p, t); } } One way to do this would be with an explicit wrapper class, as shown above. The BuilderRobot class takes a Robot in its constructor and intercepts the workOn method to make sure the tool used in any projects is of a nondestructive variety. What’s more, since the BuilderRobot wrapper implements the Robot interface, you can use a BuilderRobot instance any place you could use a Robot. The drawback to this wrapper-style BuilderRobot is evident when you modify or expand the Robot interface. Adding a method to the Robot interface means adding a wrapper method to the BuilderRobot class. Adding 10 methods to Robot means adding 10 methods to BuilderRobot. If BuilderRobot, CrusherRobot, SpeedyRobot, and SlowRobot are all Robot wrapper classes, you’ll have to add 10 methods to each of them, too. It’s a tedious, silly way to handle things. public class BuilderRobot extends MyRobot { public void workOn(Project p, Tool t) { if (t.isDestructive()) { t = Tool.RATCHET; } super.workOn(p, t); } } The above code shows another way to program a BuilderRobot. Here, we see that BuilderRobot is a subclass of MyRobot. This arrangement fixes the problem encountered in the wrapper solution demonstrated in the second code listing; modifications to the Robot interface do not require modifications to BuilderRobot. However, a new problem has arisen: Only MyRobot objects can be BuilderRobots. Before, any object implementing the Robot interface could become a BuilderRobot. Now, the linear class parentage restrictions imposed by Java prevent us from arranging classes so that an ArbitraryRobot is a BuilderRobot. A restriction Dynamic proxies offer the best of both worlds. Using dynamic proxies, you can create wrapper classes that don’t require explicit wrappers for all methods, or subclasses without strict parentage—whichever way you prefer to think of it. Dynamic proxies do, however, have a restriction. When you use dynamic proxies, the object being wrapped/extended must implement an interface that defines all the methods that are to be made available in the wrapper. But that restriction, far from being onerous, simply encourages good design. My rule of thumb is that each class should implement at least one (nonconstant) interface. Not only does good interface usage make using dynamic proxies possible, but it also encourages good program modularity in general. Using dynamic proxies The code listing shown below demonstrates the class necessary for creating a BuilderRobot using dynamic proxies. Note that the class we’ve created, BuilderRobotInvocationHandler, doesn’t even implement the Robot interface. Instead it implements java.lang.reflect.InvocationHandler, which provides just a single method, invoke. This method acts as a choke point through which any method calls on the proxy object will pass. Looking at the body of invoke, we can see that it checks the name of the method being called, and if it’s workOn, the second parameter is switched to a nondestructive tool. However, we’ve still just got an InvocationHandler with an invoke method, not the Robot object we’re looking for. The creation of the actual Robot instance is where the real magic of dynamic proxies is apparent. At no point in the source code do we define either a Robot wrapper or subclass. Nonetheless, we end up with a dynamically created class implementing the Robot interface and incorporating the Builder tool filter by invoking the code snippet found in the static createBuilderRobot method of the BuilderRobotInvocationHandler. import java.lang.reflect.Proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class BuilderRobotInvocationHandler implements InvocationHandler { private Robot wrapped; public BuilderRobotInvocationHandler(Robot r) { wrapped = r; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (“workOn”.equals(method.getName())) { args[1] = Tool.RATCHET; } return method.invoke(wrapped, args); } public static Robot createBuilderRobot(Robot toWrap) { return (Robot)(Proxy.newProxyInstance(Robot.class.getClassLoader(), new Class[] {Robot.class}, new BuilderRobotInvocationHandler(toWrap))); } public static final void main(String[] args) { Robot r = createBuilderRobot(new MyRobot()); r.workOn(“scrap”, Tool.CUTTING_TORCH); } } The code in createBuilderRobot may look a little daunting at first, but it just tells the Proxy class to use a specified class loader to dynamically create an object that implements the specified interfaces (in this case, Robot) and to use the provided InvocationHandler in lieu of traditional method bodies. The resulting object returns true in an instanceof Robot test and has all the methods you would expect to find in any class implementing the Robot interface. Interesting is the complete lack of reference to the Robot interface within the invoke method of the BuilderRobotInvocationHandler class. InvocationHandlers are not specific to the interfaces for which they’re providing proxy method implementations, and it’s certainly possible to write an InvocationHandler that can serve as the back end for many proxy classes. In this example, however, we did provide our BuilderRobotInvocationHandler with another instance of the RobotInterface as a constructor parameter. All method calls on the proxy Robot instance are eventually delegated to this “wrapped” Robot by the BuilderRobotInvocationHandler. However, although it is the most common arrangement, it’s important to understand that an InvocationHandler need not delegate to another instance of the interface being proxied. An InvocationHandler can be completely capable of providing the method bodies on its own without a delegation target. Lastly, it should be noted that the invoke method in our BuilderRobotInvocationHandler isn’t very resilient to changes in the Robot interface. If the workOn method was renamed, the nondestructive tool trap would silently fail, and we’d have BuilderRobots going about causing damage. More easily detected but nonetheless problematic would be the overloading of the workOn method. Methods with the same name but a different parameter list could result in a ClassCastException or ArrayIndexOutOfBoundsException at run time. The code below shows a fix that yields a more flexible BuilderRobotInvocationHandler. Here, we see that any time a tool is used in any method, it’s replaced by a nondestructive tool. Try to do that with subclassing or traditional delegation. import java.lang.reflect.Proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class BuilderRobotInvocationHandler implements InvocationHandler { private Robot wrapped; public BuilderRobotInvocationHandler(Robot r) { wrapped = r; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Class[] paramTypes = method.getParameterTypes(); for (int i=0; i < paramTypes.length; i++) { if (Tool.class.isAssignableFrom(paramTypes[i])) { args[i] = Tool.RATCHET; } } return method.invoke(wrapped, args); } public static Robot createBuilderRobot(Robot toWrap) { return (Robot)(Proxy.newProxyInstance(Robot.class.getClassLoader(), new Class[] {Robot.class}, new BuilderRobotInvocationHandler(toWrap))); } public static final void main(String[] args) { Robot r = createBuilderRobot(new MyRobot()); r.workOn(“scrap”, Tool.CUTTING_TORCH); } } Ideas for use Substituting tools for robots isn’t exactly a regular programming chore in most development environments, but there are plenty of other ways to use dynamic proxies. They can provide a debugging layer that effortlessly records the specifics of all method invocations on an object. They can perform bounds checking and validation of method arguments. They can even be used to swap out alternate, local testing back ends on the fly when interfacing with remote data sources. If you use good interface-driven designs, I think you’ll find more places to use dynamic proxies than you ever expected and will be pleasantly surprised at how well they fit a multitude of problems. ryanbrase Published: June 23, 2003, 12:00 AM PDT Modified: June 8, 2007, 9:44 AM PDT See more Innovation WHITE PAPERS, WEBCASTS, AND DOWNLOADS PANDEMIC RESPONSE POLICY Tools & Templates from TechRepublic Premium View This Now CHECKLIST: PC AND MAC MIGRATIONS Tools & Templates from TechRepublic Premium Download Now THE ALL-IN-ONE 2022 SUPER-SIZED ETHICAL HACKING BUNDLE Training from TechRepublic Academy Learn More SSL CERTIFICATE BEST PRACTICES POLICY Tools & Templates from TechRepublic Premium View This Now THE LINUX & DOCKER CODING BUNDLE Training from TechRepublic Academy Learn More * * * * ACCOUNT INFORMATION TechRepublic close modal SHARE WITH YOUR FRIENDS Create wrapper classes on the fly with Java dynamic proxies Check out this article I found on TechRepublic. Your email has been sent Share: Create wrapper classes on the fly with Java dynamic proxies By ryanbrase * ACCOUNT INFORMATION TechRepublic close modal CONTACT RYANBRASE Your message has been sent * | * See all of ryanbrase's content * Innovation EDITOR'S PICKS * Image: Rawpixel/Adobe Stock TechRepublic Premium TECHREPUBLIC PREMIUM EDITORIAL CALENDAR: IT POLICIES, CHECKLISTS, TOOLKITS AND RESEARCH FOR DOWNLOAD TechRepublic Premium content helps you solve your toughest IT issues and jump-start your career or next project. TechRepublic Staff Published: January 3, 2023, 8:30 AM EST Modified: January 3, 2023, 12:19 PM EST Read More See more TechRepublic Premium * Image: Nuthawut/Adobe Stock Tech & Work THE BEST PAYROLL SOFTWARE FOR YOUR SMALL BUSINESS IN 2023 Looking for the best payroll software for your small business? Check out our top picks for 2022 and read our in-depth analysis. Aminu Abdullahi Published: November 16, 2022, 11:32 AM PST Modified: January 3, 2023, 2:33 PM EST Read More See more Tech & Work * Image: WhataWin/Adobe Stock Security TOP CYBERSECURITY THREATS FOR 2023 Next year, cybercriminals will be as busy as ever. Are IT departments ready? Mary Shacklett Published: November 28, 2022, 8:09 AM PST Modified: December 23, 2022, 7:09 AM EST Read More See more Security * Image: Sundry Photography/Adobe Stock Cloud SALESFORCE SUPERCHARGES ITS TECH STACK WITH NEW INTEGRATIONS FOR SLACK, TABLEAU The company, which for several years has been on a buying spree for best-of-breed products, is integrating platforms to generate synergies for speed, insights and collaboration. Karl Greenberg Published: December 8, 2022, 6:00 AM PST Modified: December 8, 2022, 6:55 AM PST Read More See more Cloud * fizkes / iStock Software THE BEST APPLICANT TRACKING SYSTEMS FOR 2023 Organize a number of different applicants using an ATS to cut down on the amount of unnecessary time spent finding the right candidate. Brian Stone Published: November 3, 2022, 9:20 AM PDT Modified: January 3, 2023, 2:28 PM EST Read More See more Software * Image: Bumblee_Dee, iStock/Getty Images Software 108 EXCEL TIPS EVERY USER SHOULD MASTER Whether you are a Microsoft Excel beginner or an advanced user, you'll benefit from these step-by-step tutorials. TechRepublic Staff Published: August 18, 2022, 1:00 PM PDT Modified: November 11, 2022, 1:47 PM PST Read More See more Software TECHREPUBLIC PREMIUM * TechRepublic Premium HIRING KIT: ROBOTICS ENGINEER Finding the right person to fill the role of robotics engineer can be tricky because of the combination of skills required. This kit includes a detailed job description, sample interview questions and a concise want advertisement to simplify the task. From the job description: INTRODUCTION For many industries and enterprises, manufacturing of any kind is ... Downloads Published: January 9, 2023, 11:00 AM EST Modified: January 10, 2023, 12:00 PM EST Read More See more TechRepublic Premium * TechRepublic Premium SECURITY RISK ASSESSMENT CHECKLIST Organizations, regardless of size, face ever-increasing information technology and data security threats. Everything from physical sites to data, applications, networks and systems are under attack. Worse, neither an organization nor its managers need to prove prominent or controversial to prove a target. Automated and programmatic robotic attacks seek weaknesses, then exploit vulnerabilities when detected. As ... Published: January 9, 2023, 11:00 AM EST Modified: January 10, 2023, 12:00 PM EST Read More See more TechRepublic Premium * TechRepublic Premium CONTRACT WORK POLICY It’s common practice for companies to use contractors to offload work to specialized individuals or reduce costs associated with certain tasks and responsibilities. This can free up in-house staff to focus on more complex and valuable initiatives. The advantages to this practice go hand in hand with the need to carefully assess the conditions under ... Published: January 8, 2023, 11:00 AM EST Modified: January 9, 2023, 12:00 PM EST Read More See more TechRepublic Premium * TechRepublic Premium CHECKLIST: SECURING WINDOWS 11 SYSTEMS Every operating system should be appropriately secured, particularly end user workstations, which often contain or allow access to company data and upon which most employee job duties are based. To obtain the maximum security protection out of your Windows 11 deployments, follow this checklist from TechRepublic Premium. Sample: GROUP POLICY CHECKLIST Follow Microsoft recommendations for ... Downloads Published: January 8, 2023, 11:00 AM EST Modified: January 9, 2023, 1:00 PM EST Read More See more TechRepublic Premium SERVICES * About Us * Newsletters * RSS Feeds * Site Map * Site Help & Feedback * FAQ * Advertise * Do Not Sell My Information EXPLORE * Downloads * TechRepublic Forums * Meet the Team * TechRepublic Academy * TechRepublic Premium * Resource Library * Photos * Videos * TechRepublic * TechRepublic on Twitter * TechRepublic on Facebook * TechRepublic on LinkedIn * TechRepublic on Flipboard © 2023 TechnologyAdvice. All rights reserved. * Privacy Policy * Terms of Use * Property of TechnologyAdvice