Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Reflection problem: can not access a member of class java.lang.IllegalAcces

807589Feb 21 2008 — edited Aug 15 2008
package org.struts.ets.utility;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.struts.bean.FieldTrouble;
import org.struts.bean.GenericDAOBean;

public class DynamicObjectCreation
{
	public static void main(String... args)
	{
		FieldTrouble ft = new FieldTrouble();
		try
		{
			Class<?> c = ft.getClass();
			//Class<?> c = FieldTrouble.class;
			
			/*Class<?> c = null;
			try
			{
				c = Class.forName("org.struts.bean.FieldTrouble");
				
			} catch (ClassNotFoundException e)
			{
				e.printStackTrace();
			}*/
			
			Field f = c.getDeclaredField("var1");
			//f.setInt(ft, 42); // IllegalArgumentException
			f.set(ft, new String("A"));
			
			System.out.println(ft.getVar1());
			// production code should handle these exceptions more gracefully
		} catch (NoSuchFieldException x)
		{
			x.printStackTrace();
		} catch (IllegalAccessException x)
		{
			x.printStackTrace();
		}
		

}
// If I put FieldTrouble.java in any other package than the current package I am running this code from. I get the following error:

java.lang.IllegalAccessException: Class org.struts.ets.utility.DynamicObjectCreation can not access a member of class org.struts.bean.FieldTrouble with modifiers ""
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.reflect.Field.doSecurityCheck(Unknown Source)
at java.lang.reflect.Field.getFieldAccessor(Unknown Source)
at java.lang.reflect.Field.set(Unknown Source)
at org.struts.ets.utility.DynamicObjectCreation.main(DynamicObjectCreation.java:35)


I tried all possible ways of creating class as:
Class<?> c = ft.getClass(); OR
Class<?> c = FieldTrouble.class; OR

/*Class<?> c = null;
try
{
c = Class.forName("org.struts.bean.FieldTrouble");

} catch (ClassNotFoundException e)
{
e.printStackTrace();

Edited by: ..-__Kris__-.. on Feb 21, 2008 10:26 AM

Edited by: ..-__Kris__-.. on Feb 21, 2008 10:26 AM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 12 2008
Added on Feb 21 2008
10 comments
191 views