• Question 1:
    Why would the ability to set access of a variable using the setAccessible() method be a problem?
    • Highlight to see answer!
      Solution: By default java applications do not install a security manager. This means that anyone can simply call setAccessible(true) to any field in your class and change the data as they wish, presenting a huge security risk to any software using Reflection.

  • Question 2:
    Given a class:
    		  		public Class A
    				{
    					private int x;
    					public A()
    					{
    						x=0;
    					}
    					public void add(int y)
    					{
    						x += y;
    					}
    				}
    		  	

    In a java main add 1 to the field x using Reflection in 2 ways. The first being set the access of the field to allow you to simply add it directly. And second to get the method provided in the class and add 1 to x that way. You will need to define an object A in your main to do one of the methods. Also remember to get the Class of a primitive, such as an int, use Integer.TYPE.
    • Solution: (There are multiple ways you could have gotten the class)
        		static void main(String args[])
      		{
      			A obj = new A();
      			/** First Way **/
      			try
      			{
      				Class cls = Class.forName("A");
      				Field fld = cls.getDeclaredField("x");
      				fld.setAccessible(true);
      				Object value = fld.get(obj);
      				fld.set(obj,(Integer)value+1);
      			}
      			catch(Throwable e)
      			{
      				System.err.prinln(e);
      			}
      			/** Second way **/
      			Method m = cls.getDeclaredMethod("add",Integer.TYPE);
      			m.invoke(A,1);
      		}