Using reflection in EJBs

I'm a little unclear as to what the spec says about reflection, and I was hoping someone would be able to clarify it.
Section 18.1 of the spec reads:
"* The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language. The enterprise bean must not attempt to use the Reflection API to access information that the security rules of the Java programming language make unavailable."
What information is accessible through reflection that the security rules of the Java programming language make unavailable? How is use of reflection actually restricted in practice?

hi Geoff,
Reflection API provides a class java.lang.reflect.AccessibleObject which provides a way to programs using the API to suppress Java level access checking by using the setAccessible methods in the class.
I think this will break bcos application servers might use security policy which restricts this, anyway these methods are more for IDE's that need to know all the methods and attributes defined in the class.
I think this was of help to you ,
venky

Similar Messages

  • Questions on Java Reflection in EJB

    Hi,
    Recently, I use reflection technology on EJB to get/set properties of a bean.
    We need it because we need to encapsulate data in a map to transfer data between
    presentation layer and business back end(i.e. the so-called value data object).
    A bean is packed into a map as following:
    The property name of a bean becomes the key in the map, and its value becomes the
    corresponding value in the map.
    So we have to do two things:
    1)Given a bean, convert it to a map;
    2)Given a data map, assign the value to a bean
    It would be nice if we can implement the two requirements in a base class. So I use
    reflection. And succeed to achieve the goal.
    But there are two problems occured and I can't understand why.
    1)If I use Class.forName() to load the entity bean implementation class(BMP or CMP abstract
    schema) I got a ClassNotFoundException. A workaround is to jar the BMP or CMP bean class
    and place it on the classpath.
    So, I want to know why there is such restriction.
    2)For the classes java.lang.reflect.Method, java.lang.reflect.InvocationTargetException
    I reference to in bean class, the IDE(I use IntelliJ Idea) give me a
    warning: "Use java.lang.reflect.Method are not allowed in EJB". Are the methods really
    dangerous in EJB environment?
    Can anyone explain me these pluzzles?
    Thank you in advance!
    BTW, I develop under weblogic 7.0. Now, my program functions well, I just can't understand
    the above phenomena.
    Regards,
    Justine

    1) You should never directly manipulate the EJB implementation class. That class is for the container. When accessing EJBs (no matter the means), you should use the Home/Remote or Local interfaces - those your client should already have. If what you're doing is actually working for you, I can only say that you're not using EJBs properly and are not getting the actual "bang for the buck" you paid for. And you're damn lucky it hasn't blown bits all over the place...
    2) Yes, it is potentially dangerous to be dorking around with reflection on EJBs. When you're using the Home/Remote or Local interfaces, you're actually using an Object that the vendor supplies to perform the actual remote operations. Using reflection could potentially invoke one of the "hidden" vendor methods with extremely unpredictable results - like deleting your entire table.
    As for using a map for transferring data, I would strongly recommend against it, especially in this case, because you've not only lost the strong typing you get with ValueObjects, but you have to do a lot of extra work on both "sides" (client and EJB) to make sure all your data is present and/or correct.

  • Update problem when using reflection

    We have an issue when updating objects. The values are not updated in the DB when we set the values in the domain class using reflection. However when we explicitly set the values using the setter methods, update is ok.
    Here is the code for the reflection mechanism:
    UnitOfWork uow = session.acquireUnitOfWork();
    //domain class which needs to be persisted
    Student student = new Student();
    //get the clone
    Student studentClone = (Student) uow.registerObject(student);
    //copy the values from the value object into the
    // domain class using reflection
    studentClone.setVo(studentVo);
    uow.commit();
    The setVo method uses reflection to set the values (using invokeMethod). The values are set properly in the domain object. But the values are not updated when we do the commit.
    However, if we explicitly set the values in the clone using the "setter" methods, update is okay. So this code works fine.
    UnitOfWork uow = session.acquireUnitOfWork();
    Student student = new Student();      
    Student studentClone = (Student) uow.registerObject(student);
    studentClone.setName("NBA"); //set the value of name
    uow.commit();
    Any ideas would be appreciated...
    Thanks much

    TopLink 10.1.3 tracks changes through working and backup copies by default, so even if you set your changes through reflection they should be picked up. If you were using CMP 2 or EJB 3 or explicitly enabled AttributeChangeTracking, then changes set through reflective field access could be missed. In this case you should use the set methods through reflection, instead of the field directly.
    I would check your code that set the changes through reflection, perhaps it is not working as you expect. Check the state of the object after applying the changes and verify they were actually set. Also ensure that you are changing the UnitOfWork clone, not the original object.

  • ParameterNotBound exception when using reflection to set params

    I'm using the JDBC type 4 thin driver going to 8.1.6 on Win2K.
    I have an EJB method that uses reflection to do the set<type> methods on the PreparedStatement to set the positional parameters for a SQL query statement.
    The first time the method executes, I get a ParameterNotBound exception. I've used the debugger to determine that all the parameters are bound - at least the set<type> methods have been called.
    The wierd thing is that all subsequent calls to the the SQL query method work fine.
    Does anyone here know where in the PreparedStatement class are the parameters bound. What data element? I'm trying use the debugger to determine what's different the first time the method is called.
    Thanks,
    Rich Bolen

    Congrats Darek!
    That function really works... here is my program test:
    package integracao.sap.teste;
    import java.util.Properties;
    import integracao.sap.config.ConfigUtil;
    import integracao.sap.funcao.RFC_READ_TABLE;
    import com.sap.mw.jco.IRepository;
    import com.sap.mw.jco.JCO;
    public class TestJCOError {
         private static Properties config;
         private static JCO.Client createJCOClient(){
              JCO.Client client = JCO.createClient(config.getProperty("numClient"), config.getProperty("user"), config.getProperty("password"), "EN", config.getProperty("host"), config.getProperty("numPrograma"));
              return (client);
    @param args
         public static void main(String[] args) {
              config = ConfigUtil.getConfig();
              JCO.Client client = createJCOClient();
              client.connect();
              IRepository repository = JCO.createRepository("REP", client);
              JCO.Function func = RFC_READ_TABLE.createFunction(repository);
              func.getImportParameterList().setValue("MARC", "QUERY_TABLE");
              func.getImportParameterList().setValue(";",    "DELIMITER");
              func.getTableParameterList().getTable("OPTIONS").appendRow();
              func.getTableParameterList().getTable("OPTIONS").setValue("MATNR = '000000000000000011'", "TEXT");
              func.getTableParameterList().getTable("FIELDS").appendRow();
              func.getTableParameterList().getTable("FIELDS").setValue("MATNR", "FIELDNAME");
              client.execute(func);
              JCO.Table table = func.getTableParameterList().getTable("DATA");
              System.out.println("NumRows: " + table.getNumRows());
              System.out.println("Content: " + table.getValue("WA"));
    Result:
    NumRows: 1
    Content: 000000000000000011
    Hope it helps everybody!
    Regards,
    Danilo Andrade

  • How can i get all java class names from a package using reflection?

    hi,
    can i get all classes name from a package using reflection or any other way?
    If possible plz give the code with example.

    You can't, because the package doesn't have to be on the local machine. It could be ANYWHERE.
    For example, via a URLClassLoader (ie from the internet) I could load a class called:
    com.paperstack.NobodyExpectsTheSpanishInquisitionI haven't written it yet. But I might tomorrow. How are you going to determine if that class is in the package?
    This subject comes up a lot. If you want to do something a bit like what you're asking for (but not quite) there are plenty of threads on the subject. Use google and/or the forum search facility to find them.
    But the answer to your question, as you asked it, is "you can't do that".

  • Insert data into table from JSP page using Entity Beans(EJB 3.0)

    I want to insert data into a database table from JSP page using Entity Beans(EJB 3.0).
    1. I have a table 'FRIENDS', (in Oracle 10g database).
    2. It has two columns, 'NAME' and 'CITY'. Both have datatype strings(varchar2).
    3. Now from a JSP page, having two textfields, 'NAME' and 'CITY', I want to insert data into table 'FRIENDS'.
    4. In between JSP and database is a Entity Bean(EJB 3.0) and a stateless session bean.
    5. I am using JDev as editor.
    Please provide me code ASAP or link with similar example.
    Thank you.
    Anurag

    Hi,
    I am also trying that scenario. So u can
    Post the jsp form data to a Servlet which will act as a Controller.
    In the servlet invoke the business method.
    Similar kind of app is in www.roseindia.net
    Hope this would help u.
    Meanwhile if u get any optimal solution, pls post it.
    Thanks,
    Happy Java Coding.

  • How am I able to use an injected EJB in a Managed Bean Constructor?

    JSF 1.2
    EJB 3.0
    Glassfish v1
    Summary:
    Managed bean injected EJB is null when referencing EJB var in constructor.
    Details:
    In my managed bean, I have a constructor that tries to reference an injected EJB, such as:
    public class CustomerBean implements Serializable {
    @EJB private CustomerSessionRemote customerSessionRemote;
    public CustomerBean() {
    List<CustomerRow> results = customerSessionRemote.getCustomerList();
    }The call within the constructor to customerSessionRemote is null - I've double checked this in Netbeans 5.5.
    How am I able to use an injected EJB in a Managed Bean Constructor?
    Thanks,
    --Todd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    OK, I was reading the article Web Tier to Go With Java EE 5: A Look at Resource Injection and I understand your statement too.
    Is there any way possible to Inject the EJB prior to the bean instance creation at all?
    Maybe, I need to approach it with the old fashion Java EE 1.4 route and using JNDI in the PostConstruct annotated method to reference the EJB in the managed bean.
    This had to been thought out before, I don't understand why a manged bean's life cycle places any injections at the end of the bean creation.
    Also, now that I understand that the @PostConstruct annotated method will be called by the container after the bean has been constructed and before any business methods of the bean are executed.
    I am trying to reference my EJB as part of the creation of the managed bean.
    What happens: the JSF page loads the managed bean and I need to populate a listbox component with data from an EJB.
    When I try to make the call to the EJB in the listbox setter method, the EJB reference is null.
    Now, I'm not for sure if the @PostConstruct annotation is going to work... hmmmm.
    ** Figured it out. ** I just needed to move the EJB logic that was still in the setter of the component I wanted to populate into the annotated PostConstruct method.

  • Calling a pkg from managed code and then using reflection to call a method from a script task

    Hi we run 2012 std.  I have some pretty good evidence that when I call my pkg from a .net service, a script component in that pkg fails when trying 2 use reflection to load and invoke our .net message history method.  The exception is either on
    the invoke or in the message history method.  I suspect its in the method but will take additional steps 2 verify.
    But when I run the pkg stand alone, it has no problem and the method does what it is supposed 2 do.
    There r no vars passed from the service to the pkg.  I wonder if its a managed to unmanaged to managed issue that the community is already aware of.  If not, my apologies 4 posting this quickly.
    I'll post more info here as I collect it. 

    we have 2 theories after showing the exception trace to folks who r more adept at managed code.
    the first is related to the fact that our 3rd party dlls (I think entity framework is included in these) r older versions.  I don't want to discount this theory but we have some evidence already that this might not be true.
    I hope I can do justice to the 2nd theory but will make it clearer and clearer as I get a better understanding.  I believe this is what Arthur was saying and I applaud his instincts.  They explained that .net is so "smart" that it detected
    a change in namespace  (ie context as Arthur said) and purposely threw an exception 2 save us from ourselves.  The workarounds discussed were a bit over my head but I will continue trying to better understand it.  The fact that many of the methods
    we call after reflection r now merged into one assembly seemed relevant to the discussion and possible workarounds.   
    this link came up in their discussion and I believe the bottom line here is that by qualifying assembly names further (in config?)r, a workaround is possible. 
    http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx  .
    This link came up as well and has something to do with ILMerge and workarounds to ILMerge. 
    http://elegantcode.com/2011/04/02/dynamically-load-embedded-assemblies-because-ilmerge-appeared-to-be-out/  .
    Finally, this link came up and seems to have something to do with embedding your dlls in one assembly without them losing their identity.
    http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx
    I'll post more here as we muddle thru this.

  • XML document creation using reflection

    Hi all,
    I'm tyring to write a class which creates an XML document from objects passed in. For example, you call the add(Object) method and it takes your object, uses reflection, then outputs XML like this...
    <fieldName>fieldValue<fieldName>
    The only problem is that after looking through this forum I am a little concerned about the performance of my proposed solution (using reflection).
    The class will be used in a batch process which processes millions of objects (to generate a whopping XML file that'll be sent on for further processing by a third party).
    Is there a better way to do this than by using reflection?
    This class is going to be used by multiple batch processes hence there will be lots of different object types passed (they'll also be new ones in the future that we don't even know about yet) hence my reflection choice.
    Thanks,
    Chris

    The only problem is that after looking through this
    forum I am a little concerned about the performance of
    my proposed solution (using reflection).The only way that you'll know for sure is if you try it out. Write the code, test it, then run it in a profiler to find out where the performance problems (if any) are.
    Is there a better way to do this than by using
    reflection?Probably not, if you want to pass any arbitrary object to it.
    One possible alternative is to have "XML aware" objects: define an interface WritesXML, that defines a method toXML(). You then check to see whether the given object implements this interface, and if it does you simply call the method, otherwise you use reflection.
    Another alternative, assuming that your objects follow the Bean pattern, is to create "XML-ifiers" on the fly, similar to the way an app-server handles JSPs. First time you see an object you create a class that will write it to XML, then compile this class and invoke it for all subsequent objects. This will require that you have a JDK installed on the runtime machine, that the objects follow the Bean pattern, and that the number of instances of a given class are very high.
    This class is going to be used by multiple batch
    processes hence there will be lots of different object
    types passed (they'll also be new ones in the future
    that we don't even know about yet) hence my reflection
    choice.Sounds like a good reason to use reflection.

  • Using reflection...

    Hi,
    I have one class. to run that, I am calling like the following...
    java -classpath ;.;\comdotebo; com.pack1.MyClass
    now I want to take the reference of this class(dynamically) using reflection pakcage like the following...
    Class cla = Class.forName("com.pack1.MyClass");
    but to take the class reference I need to set the classpath;
    so how can i set the classpath dynamically.
    please give proper solution
    thanks
    Raja Ramesh Kumar M

    here the case is we know both the class and the class path at run time only
    for ex: see the following.....
    I have two files .....
    1) c:\dir1\com\pack1\MyClass1.class
    2) c:\dir2\com\pack2\MyClass2.class
    now I want to access both the classes using reflection from ...
    c:\dir3\com\pack3\MainClass.class
    using reflection, we can write the following...
    Class clas1 = Class.forName("com.pack1.MyClass1");
    if I am taking like this, then I am getting ClassNotFoundException.
    becoz, for that we have to give the proper classpath before running the program.
    like.
    set classpath=%classpath%;.;c:\dir1;
    but my problem is here I know the the class name (for ex: com.pack1.MyClass1) and the classpath (ex: c:\dir1)
    at runtime only.
    so please tell me how to solve this problem
    regards
    Raja Ramesh Kumar

  • Do i have to use JNDI with EJBS?

    Hi
    I want to use JNDI to lookup a system which i will send messages to using JMS. I would like to have some java classes on Tomcat to do the job. But...whenever i hear about JNDI it is always in relation to EJBs. Can i only use JNDI with EJBS?
    If i can use JNDI is there anything important i need to know about.
    Thanks in advance!
    San H.

    You can definitely use JNDI outside of EJB's - in particular, it's a great interface for dealing with LDAP servers, even securely, and can also be used for DNS interfacing, COS, RMI registries, etc.
    While JNDI was chosen as the method by which J2EE components can locate other components in a distributed environment, it's by no means limited to that task :) It's a wonderful API, and in terms of things you need to know, most everything is covered fairly well at the JNDI tutorial in the various trails that are mapped out there.
    http://java.sun.com/products/jndi/tutorial/
    Good luck!
    James
    James Manning | Principal Engineer
    Porivo Technologies, Inc.
    919.806.0566 | [email protected]
    http://www.porivo.com/
    Measuring end-to-end Web performance.
    Register for a FREE Performance appraisal:
    http://www.porivo.com/peerReview/eval.html

  • Do i have to use JMS with EJBS?

    Hi
    I want to use JMS as a messaging system (a queue) between my system and someone elses. I would like to have some java classes on Tomcat to do the job. But...whenever i hear about JMS i always hear it in relation to EJBs. Can i only use JMS with EJBS?
    If i can use JMS is there anything important i need to know about.
    Thanks in advance!
    San H.

    As far as I understand you are use JNDI and JMS is not bound with EJB's. These are java API's which are independent. Like JDBC you can use with Servlets, Applets, standalone applications, EJB, JMS etc etc.......
    In the same way you can use JNDI and JMS with diferent API. And the important feature of Java is that all java API interact with each other when these are independent. I would appricate comments of everyone......................Thanks

  • How to create an array using reflection.

    How to create an array using reflection.
    I want to achive something like this,Object o;
    o = (Object)(new TestClass[10]);but by use of reflection.
    To create a single object is simple:Object o;
    o = Class.forName("TestClass").newInstance();But how do I create an array of objects, when the class of objects is known only by name? (Can't use Object[] because even though an Object[] array can be filled with "TestClass" elements only, it Cannot be casted to a TestClass[] array)
    Anybody knows?":-)
    Ragnvald Barth
    Software enigneer

    Found it!
    the java.lang.reflect.Array class solves it!
    Yes !!!

  • How To: Use reflection to create instance of generic type?

    I would like to be able to use reflection to instantiate an instance of a generic type, but can't seem to avoid getting type safety warnings from the compiler. (I'm using Eclipse 3.1.1) Here is a trivial example: suppose I want to create an instance of a list of strings using reflection.
    My first guess was to write the following:
    Class cls = Class.forName("java.util.ArrayList<String>");
    List<String> myList = cls.newInstance();The call to Class.forName throws a ClassNotFoundException. OK, fine, so I tried this:
    Class cls = Class.forName("java.util.ArrayList");
    List<String> myList = cls.newInstance();Now the second line generates the warning "Type safety: The expression of type List needs unchecked conversion to conform to List<String>".
    If I change the second line to
    List<String> myList = (List<String>)cls.newInstance();then I get the compiler warning "Type safety: The cast from Object to List<String> is actually checking against the erased type List".
    This is a trivial example that illustrates my problem. What I am trying to do is to persist type-safe lists to an XML file, and then read them back in from XML into type-safe lists. When reading them back in, I don't know the type of the elements in the list until run time, so I need to use reflection to create an instance of a type-safe list.
    Is this erasure business prohibiting me from doing this? Or does the reflection API provide a way for me to specify at run time the type of the elements in the list? If so, I don't see it. Is my only recourse to simply ignore the type safety warnings?

    Harald,
    I appreciate all your help on this topic. I think we are close to putting this thing to rest, but I'd like to run one more thing by you.
    I tried something similar to your suggestion:public static <T> List<T> loadFromStorage(Class<T> clazz) {
        List<T> list = new ArrayList<T>();
        for ( ...whatever ...) {
           T obj = clazz.newInstance();
           // code to load from storage ...
           list.add(obj);
        return list;
    }And everything is fine except for one small gotcha. The argument to this method is a Class<T>, and what I read from my XML storage is the fully qualified name of my class(es). As you pointed out earlier, the Class.forName("Foo") method will return a Class<?> rather than a Class<Foo>. Therefore, I am still getting a compiler warning when attempting to produce the argument to pass to the loadFromStorage method.
    I was able to get around this problem and eliminate the compiler warning, but I'm not sure I like the way I did it. All of my persistent classes extend a common base class. So, I added a static Map to my base class:class Base
       private static Map<String, Class<? extends Base>> classMap = null;
       static
          Map<String, Class<? extends Base>> map = new TreeMap<String, Class<? extends Base>>();
          classMap = Collections.synchronizedMap(map);
       public static Class<? extends Base> getClass(String name)
          return classMap.get(name);
       protected static void putClass(Class<? extends Base> cls)
          classMap.put(cls.getName(), cls);
    }And added a static initializer to each of my persistent classes:class Foo extends Base
       static
          Base.putClass(Foo.class);
    }So now my persistence code can replace Class.forName("my.package.Foo") with Base.getClass("my.package.Foo"). Since Foo.class is of type Class<Foo>, this will give me the Class<Foo> I want instead of a Class<?>.
    Basically, it works and I have no compiler warnings, but it is unfortunate that I had to come up with my own mechanism to obtain a Class<Foo> object when my starting point was the string "my.package.Foo". I think that the JDK, in order to fully support reflection with generic types, should provide a standard API for doing this. I should not have to invent my own.
    Maybe it is there and I'm just not seeing it. Do you know of another way, using reflection, to get from a string "my.package.Foo" to a Class<Foo> object?
    Thanks again for your help,
    Gary

  • Working around unchecked conversions when using reflection

    I think I've convinced myself that there's no way around this issue when using reflection and Generics, but here's the issue:
    Suppose I've got a method that uses reflection to compare an arbitrary property in
    an arbitrary pair of beans (of the same class).
    public static <T> int compare(T bean0, T bean1, String prop) throws Exception {
         Method m = bean0.getClass().getMethod(
                   "get" + prop.substring(0,1).toUpperCase() +
                   prop.substring(1));
         Object o0 = m.invoke(bean0);
         Object o1 = m.invoke(bean1);
         if (o0 instanceof Comparable &&
             o1 instanceof Comparable &&
             (o1.getClass().isAssignableFrom(o0.getClass()) ||
              o0.getClass().isAssignableFrom(o1.getClass()))) {
              return ((Comparable)o0).compareTo(o1); // compiler warning
         } else {
              return o0.toString().compareTo(o1.toString());
    }There's no way that, in general, when using reflection to invoke methods, that you can coerce the types to avoid compile-time type safety warnings. I think the above code is guarranteed not to throw a runtime ClassCastException, but there's no way to write the code so that the compiler can guarrantee it. At least that's what I think. Am I wrong?

    Ok it looks like you're dealing with a classloader issue. when you call that method, it is the equivelant of calling
    Class.forName("Box", true, this.getClass().getClassLoader())The exception is thrown when your class's classloader cannot find the class box. try putting 'null' there
    Class.forName("Box", true, null)and it will request the bootstrap classloader to load the class. just make sure you have permission :
    If the loader is null, and a security manager is present, and the caller's class loader is not null, then this method calls the security manager's checkPermission method with a RuntimePermission("getClassLoader") permission to ensure it's ok to access the bootstrap class loader. (copied from the API)

Maybe you are looking for

  • IMac 2013 and PC via Thunderbolt in TDM

    Hi all, today I do have an IMAC 2010 connecte to a PC via a display port cable. This works fine and is a perfect solution to limit the space used on the Desk. So now I am planning to move on to an IMAC 2013. As those new models do no longer supply a

  • Problem in executing query in RSCRM_BAPI  & output in application server!

    hi Experts, We executed a query using RSCRM_BAPI transaction and write it to the application server.We found the following problem. In the query we have restricted the keyfigures such that each have 2 decimal places but when we execute the query usin

  • RAW better than JPG??? Nah!

    Here a picture I took with my Fuji Finepix. A Kingfisher sitting about 6, 7 m away from me on a tree. I took the Picture as JPG+RAW. Here what the JPG looks like and here the best I could make out of the RAW image RAW doesnt seem to be necessarily be

  • Mavericks won't install and iTunes/App Store always quit unexpectedly.

    Let me start by saying that I am not very computer-savvy. That being said, I don't mess with my computer very much so I feel like this should be an easy fix. The problem started a few days ago when my macbook froze and then shut down. When I booted i

  • Convert FCE HD project into Flash for web?

    I would like to use FCE HD to edit/create some footage and then convert it to Flash so anyone on any platform can view it on the web. Is this possible?