Java reflection and singletons

Using java reflection and singletons .. anyone seen this being used?

I've solved it
I had a singleton but then it turned out i had to use reflection instead, i tried to used reflection on 3 methods but the session value within was null upon the second method call. Relfection was re-creating the Object.
Sorry for wasting your time.

Similar Messages

  • Java reflection and parameter's names

    hi, I have to extract from a method of a given class all types and names of the parameters, i've tryed to use java reflection function:
    Method[] metodo = temp.getDeclaredMethods();
    for (int i = 0; i < metodo.length; i++) System.out.println(metodo.toString());
    and the output is:
    public void DinamicLoad.function1.method1()
    public void DinamicLoad.function1.method2(java.lang.String)the function extract only the parameter's type, not his name

    Probabily all the "dozens, hundreds, thousands of
    other people who use reflection" knows very well
    classes that they use.
    Imagine to produce a class from a wsdl file, how can
    you know the content?
    How can you pass parameters if you know only the type
    and not the MEANING?When building classes from XML it's rare to use the constructor to convey the attributes, far more often each attribute is set independantly using a single argument setter with a signature like:
    public void setMyAttribute(String value) {Hence attribute names (e.g. myAttribute) are normally compared against method names, not parameter names.
    If constructors are to be used then parameters will be supplied in order.

  • Java Reflection and dynamic class loading

    I am trying to load my classes 'dynamically' using java reflection, which is a feature absolutely necessary for my webapp. I could not get this to work as of yet. Could someone please give me a piece of sample code that would do the following :
    - return the value (String) of known method y from class x
    - class x is only known at runtime (from the query-string in this case)
    - method y is known
    Thanks in advance.
    cheers,
         Tom
    PS: Please do not give me any links to tutorials/articles that do not do the EXACT thing that I asked for. Thank you.

    tried it, but it always gives me a MethodNotFoundException, because its trying to find my class in java.lang.String for some reason...
    heres part of the code (its an altered version of the code given in the invoke tutorial):
    public String getMethodReturnValue(String methodName, String className) {
    String result = null;
    Class theModuleClass = String.class;
    Class[] parameterTypes = new Class[] {};
    Method concatMethod;
    //Object[] arguments = new Object[] {parameters};
    try {
    concatMethod = theModuleClass.getMethod(methodName, null);
    result = (String) concatMethod.invoke(createObject(className), parameterTypes);
    } catch (NoSuchMethodException e) {
    result = e.toString();
    } catch (IllegalAccessException e) {
    result = e.toString();
    } catch (InvocationTargetException e) {
    result = e.toString();
    return result;
    private Object createObject (String className) {
    Object object = null;
    try {
    Class classDefinition = Class.forName(className);
    object = classDefinition.newInstance();
    } catch (Exception e) {}
    return object;
    Thanks for any help!
    -Tom

  • Question about java reflection and "int" type

    hi, using reflections I should invoke a Method (meth3) that have as parameter an INT type (not integer). I've tryed with this code:
                        int num = 3;
                        Class[] vettClax = {int.class};
                        Object[] vettParam = {num};
                        Method meth3 = temp.getMethod("meth3", vettClax);
                        meth.invoke(o, vettParam);My problem is that the int value is catched as an Integer value and reflection doesn't found a method that accept an INTEGER as parameter, who can help me?

    Works fine when I try it.
    public class t
        public static void main(String args[])
         throws Exception
         Class temp = t.class;
         t o = new t();
         int num = 3;
         Class[] vettClax = {int.class};
         Object[] vettParam = {num};
         Method meth = temp.getMethod("meth3", vettClax);
         meth.invoke(o, vettParam);
        public void meth3(int n)
         System.out.println("hello " + n);
    }Is your meth3() public?

  • Performance difference between java.beans.Expression and Java Reflection

    What is the Performance difference between using java.beans.Expression class and Java Reflection classes like Class,Method ??

    negligible

  • Java Reflection

    Hi Every1....i have a problem with java reflection n hope some1 will be able to resolve this me.
    I am getting the name of the child class as a string argument.
    eg String classname = this.getattributes().get("classname");
    I need to dynamically create the object of this instance using the classname and call a specific method...i know the name of the base class but the base class doesnt have the method i need....i m not allowed to redesign the base class...
    plz help

    but the problem is getting the method nameIf you don't have the method name what exactly is the plan? You've gotta have something ...
    .....i have the object of base class with meActually the object is an instance of the derived class ...
    ....and the method i
    need is in the child class.....so how do i invoke the
    method???Sigh. You can lead a horse to water but you can't make him drink. See
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object,%20java.lang.Object...)

  • Difference b/w Java Class and Bean class

    hi,
    can anybody please tell me the clear difference between ordinary java class and java Bean class. i know that bean is also a java class but i donno the exact difference between the both.
    can anybody please do help me in understanding the concept behind the bean class.
    Thank u in advance.
    Regards,
    Fazlina

    While researching this question, I came across this answer by Kim Fowler. I think it explains it better than any other answer I have seen in the forum.
    Many thanks Kim
    Hi
    Luckily in the java world the definition of components is a little
    less severe than when using COM (I also have, and still occasionaly
    do, worked in the COM world)
    Firstly there are two definitions that need to be clarified and
    separated: JavaBean and EnterpriseJavaBean (EJB)
    EJB are the high end, enterprise level, support for distributed
    component architectures. They are roughly equivalent to the use of MTS
    components in the COM/ COM+ world. They can only run within an EJB
    server and provide support, via the server, for functionality such as
    object pooling, scalability, security, transactions etc. In order to
    hook into this ability EJB have sets of interfaces that they are
    required to support
    JavaBeans are standard Java Classes that follow a set of rules:
    a) Hava a public, no argument constructor
    b) follow a naming patterns such that all accessor and modifier
    functions begin with set/ get or is, e.g.
    public void setAge( int x)
    public int getAge()
    The system can then use a mechanism known as 'reflection/
    introspection' to determine the properties of a JavaBean, literally
    interacting with the class file to find its method and constructor
    signatures, in the example above the JavaBean would end with a single
    property named 'age' and of type 'int' The system simply drops the
    'set' 'get' or 'is' prefix, switches the first letter to lower case
    and deduces the property type via the method definition.
    Event support is handled in a similar manner, the system looks for
    methods similar to
    addFredListener(...)
    addXXXListener
    means the JavaBean supports Fred and XXX events, this information is
    particularly useful for Visual builder tools
    In addition there is the abiliity to define a "BeanInfo' class that
    explicitly defines the above information giving the capability to hide
    methods, change names etc. this can also be used in the case where you
    cannot, for one reason or another, use the naming patterns.
    Finally the JavaBean can optionally - though usually does - support
    the Serializable interface to allow persistence of state.
    As well as standard application programming, JavaBeans are regularly
    used in the interaction between Servlets and JSP giving the java
    developer the ability to ceate ojbect using standard java whilst the
    JSP developer can potentially use JSP markup tags to interact in a
    more property based mechanism. EJB are heaviliy used in Enterprise
    application to allow the robust distribution of process
    HTH.
    Kim

  • Code generation through Java Reflection

    Hi
    I am after some clarification about the possibility of mapping of method outputs to other method inputs, using java reflection.
    The java objects are described in an XML based language (called DAML) as follows
    <java:Method rdf:ID="meth1" java:priority="1">
    <java:methodName>buildQuery</java:methodName>
    <java:parentClass>afsw.query.QueryBuilder</java:parentClass>
    <java:methodParameters rdf:parseType="daml:collection">
    <java:Parameter>
    <java:inORout>input</java:inORout>
    <java:type>java.util.Hashtable</java:type>
    </java:Parameter>
    </java:methodParameters>
    </java:Method>
    and I want to map them back to method calls and instantiations, so to be able to generate code on the fly. I need to know if its is possible to pass the output of a method such as getQuery() which in this case is a Document to the input of constructor MsgModule as in the following example:
    Document queryDoc =qc.getQuery();
    MsgModule mg= new MsgModule(queryDoc);
    regards
    Charlie

    This is possible. What you need to do in the 'new' instance case is to find the best constructor. So let's say you have Class clazz, the class you want to create a new instance of, and Class[] params, an array of objects to pass in the constructor. Using the Class api you can do:
    Constructor constructor = clazz.getConstructor(params);The getConstructor method will only return an exact match. Let's say one of the parameters was a subclass of an class that is allowable in the constructor. You can get all the constructors via clazz.getConstructors() and get all the parameters types via Constructor.getParameterTypes() and check to see if the params you passed in are compatible. You can use Class.isAssignableFrom() to help resolve this. Once you find the constructor, use Constructor.newInstance(params) to create the new instance. Hope this helps.

  • MDM 5.5 SP04 Java API and Web Service Documentation

    Is there documentation available that reflects the SP04 changes to the Java API, and the web services that are now available?
    As of this morning, service marketplace contained spotty SP04 docs.
    Thanks in advance,
    Mike

    Mike,
    A cookbook would be wonderful (I think our developers would throw a party)!
    An updated object model (as a preface to the user guide) for the legacy API (MDM4J.jar) AND the new "rebranded" API (mdm-*.jar) would also work.
    I've been reduced to comparing the SP3 & SP4 javadocs
    One fun approach that appears to be working for us, is to model each process using the DataManager, and try to duplicate that exactly via the corresponding API objects (e.g. the simple Connect-Find Table-Search Table-View Result Set-View Record-CheckOut/Upsert/Validate/CheckIn dance).  New features in the DataManager reveal themselves a little more readily
    Good luck,
    ...Dee

  • Reflection and generics

    Hi all:
    I am working with the generic and reflection stuff. Well the problem is that in one of my clases I have a data
    private Vector<nAryNode<T>> childs;
    .....where nAryNode<T> is a class I created using generics.
    Now when I want to initialize my childs variable, well the easy thing to do is:
    childs = new Vector<nAryNode<T>>(3)But I want to initialize it using reflection and my code is:
            Class v = Class.forName("java.util.Vector");
            Class[] argVector = new Class[] {int.class};
            Constructor consVector = v.getConstructor(argVector);
            Object[] arguments = new Object[] {new Integer(n)};
            childs = (Vector<nAryNode<T>>)consVector.newInstance(arguments);Finally when I compile I got the annoying warning message
    nAryNode.java:29: warning: [unchecked] unchecked cast
    found : java.lang.Object
    required: java.util.Vector<nAryNode<T>>
    childs = (Vector<nAryNode<T>>)consVector.newInstance(arguments);
    ^
    Well my program can run, but I would like to make disappear that message. Please if you have any suggestions for me, it will be great. Thx

    AFAIK, there is no solution to this currently because arrays of generic types are not allowed. Therefore "consVector.newInstance(arguments);" return a Vector and cannot be made to return "Vector<Integer>" (or whatever)

  • Java reflection (interesting question)

    hi folks,
    class A {
    void foo() {
    Class B overrides method foo() in A
    class B extends A {
    void foo() {
    Now i create a object of class B and assign to A
    A aref = new B();
    aref.foo() will call method foo()of class B. //polymorphism
    Using reflection, is it possible to call method foo() of class A using the handle aref.
    thanks
    venkat

    hi bondvenky,
    What abt the answer for my original question. How to
    access the base class methods using the handle for
    child class object using reflection ?as far as i know, this isn't possible - your next question is probably going to be "why". It certainly seems slightly surprising that you can't do this, but you can access private methods. Unless you consider the latter a weaker way of breaking encapsulation (!?).
    what was the sun's purpose behind allowing access to
    the private methods of an object using Java
    Reflection? good question.. its very useful but on the other hand i can't think of a time i've used it that couldn't be classed as a hack.
    Is it not a security threat to java security model?it doesn't break anything - ie its not a security loophole. It links in with your question above though - would it have been possible/useful to not allow it period?
    sorry for the vague answers :(
    asjf

  • Java reflection - any disadvantages

    1. Are there any disadvantages in using java reflection api (too much)?
    2. How do obfuscators deal with reflection based applications?
    Thanks
    Santosh

    Sorry, i wanted to know how the code
    Object obj = new MyClass();
    is different from
    Class clazz = Class.forName("MyClass");
    Object obj = clazz.newInstance();
    at the byte-code level.
    That is, in both the cases the classloader has to
    search for MyClass and invoke the constructor. Hope I
    am clear :)I don't think there is any difference as far as performance is concerned between the above mentioned methods for instantiating the object of MyClass.
    But here is what is generally said about using reflection(u can find it on google):
    ===============================================================
    Don?t overuse the Reflection API. Programs that use it are more difficult to understand and maintain. In addition, accessing fields and calling methods through the Reflection API is slower than using them in the ?normal? way, so use reflection only when it is really necessary.
    ===============================================================
    We too had concerns about reflection's performance, but as long as you cache the lookups, reflection is very fast. What is slow is doing things like looking up a method on a class or looking up an instance member. We do all these lookups once and then cache the results.
    ===============================================================
    Why is it slow as stated above? - Maybe because flexibility always comes at a price !!! Maybe the internal implementation of the call sequence by the JVMs is such that it cannot be implemented any faster...

  • Can Java reflect not only .Class file

    Hi' i'm newbie in this topic, i'm really appreciate if somebody can help me..cos i'm really stuck in here...
    My Problems are :
    1. i want to ask about this, can Java reflect from .java file?
    2. i'm using Eclipse IDE, i'm really interesting about how JTree or Package Explorer in Eclipse can always displaying update information about class structure? but .java files not compiled, how can? if Eclipse using reflection, .java files must be compiled first, correct me if i'm wrong?
    The fact is Eclipse don't have to compiled .java files to get the update information about class structure and displaying in JTree or package Explorer...how implement like this?
    what i mean like this :
    ex : if i type int x = 100; (not only int, it could be anything else..) at the working files, JTree or Package Explorer in Eclipse can always update the informasion about class structure, but .java files not compiled..
    i hope my question are easy to understand, i really need some help..
    Thanks a lot..

    hey, thanks for the answers, but i would like to ask :
    1) Eclipse performs background compilation of the Java sources, then performs reflection on those temporary classes++ if i'm using this way, how about the performance? seems that it will be compiled all the time right?
    2) Eclipse has access to the results of the Java source code parser, and can extract the information from the java syntax parser, before it gets to the compilation stage.++ how to implement this? what do you mean about java syntax parser?
    do you know where i can find any article about this?
    thanks a lot again...

  • About reflection and packages

    Bonjour a tout le monde!
    Could someone tell me how to retrieving the classes stored in a package.
    I've a code like this:
    Package p  = Package.getPackage("java.net");and I'm looking for a way to get a list of Class objects present in 'p'
    HELP!!!

    Neither article addresses the original poster's question or the problem he wants to solve. In which circumstances pointing out that "you can't do that" is reasonable.
    The nearest compromise (and the technique that I believe Eclipse uses) is to actually determine from the JAR files provided in the classpath what classes are immediately available. That's not easy to do, and certainly not addressed by the sort of reflection API method that the OP was looking for.
    instead of just automatically negating everythingI had read the articles that you posted, and you were implying that the OP's problem could be solved using the classloader. Since this was wrong I don't think I was "automatically" negating everything.
    Dave.

  • Java Controls as singletons

    Hi everybody.
    Can i use Java Control Factories to treat Java Controls as singletons ? Is there any issue about multiple threads acessing the same instance of (Built-in or Custom) Java Controls ?
    When i use the following structure:
    Page Flow -> Custom Java Control -> Built-in Java Control
    and my Custom Java Control is "stateless". Can i "share" the same instance of Custom Java Control between different Page Flows ? How should i proceed to do it ?
    Thanks in advance.

    Hi Daniel
    I don't think java controls are multithreaded and also since they are executed as EJB's you cannot do threading there.
    Basically java controls (jcs) internally gets invoked within a EJB container so you can say that JCS kind of becomes an EJB and so have the EJB pool, cache funactionality so eventually we reuse the instances of the ejb for incoming requests.
    If the control is stateless then the EJB wrapper for the control code will be a stateless EJB and hence we reuse the instances as they become free after the method execution.
    Similarly if the control is stateful then we use Entity beans(BMP container bean) which saves the state in the database and maintains it. In essence you do get the advantage of pooling, transaction etc
    Thanks
    Vimala

Maybe you are looking for