27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 14 | Java<br />

14.5 Explain what object reflection is in Java <strong>and</strong> why it is useful.<br />

pg 78<br />

SOLUTION<br />

Object Reflection is a feature in Java which provides a way to get reflective information about<br />

Java classes <strong>and</strong> objects, such as:<br />

1. Getting information about methods <strong>and</strong> fields present inside <strong>the</strong> class at run time.<br />

2. Creating a new instance of a class.<br />

3. Getting <strong>and</strong> setting <strong>the</strong> object fields directly by getting field reference, regardless of<br />

what <strong>the</strong> access modifier is.<br />

1 import java.lang.reflect.*;<br />

2<br />

3 public class Sample {<br />

4 public static void main(String args[]) {<br />

5 try {<br />

6 Class c = Class.forName(“java.sql.Connection”);<br />

7 Method m[] = c.getDeclaredMethods();<br />

8 for (int i = 0; i < 3; i++) {<br />

9 System.out.println(m[i].toString());<br />

10 }<br />

11 } catch (Throwable e) {<br />

12 System.err.println(e);<br />

13 }<br />

14 }<br />

15 }<br />

This code’s output is <strong>the</strong> names of <strong>the</strong> first 3 methods inside <strong>the</strong> “java.sql.Connection” class<br />

(with fully qualified parameters).<br />

Why it is useful:<br />

1. Helps in observing or manipulating <strong>the</strong> runtime behavior of applications.<br />

2. Useful while debugging <strong>and</strong> testing applications, as it allows direct access to methods,<br />

constructors, fields, etc.<br />

2 2 9<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Knowledge Based

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!