Using reflection to get method body

Hi,
I'm just getting into this side of program and while I understand the use of reflection in oredr to obtain the constructor and method, parameters, fields etc I was wondering if its possible to grab the method body and copy it into a string.
So for example in the following class...
class MyClass
private String str;
MyClass(){}
public String MyMethod(String s)
str=s;
str=str+" was the String";
System.out.println(str);
return str;
...I need to capture just this code..
str=s;
str=str+" was the String";
System.out.println(str);
return str;
...as a string
The reason i need to do this is that I'm programming a mechanism for storing objects and their methods using JDBC.. I could use object serialisation and store as a blob, but I'm wanting to store the attributes of a class as seperate parts so I can retrieve bits of code from the database at some later time.
Thanks for any help you might give me
peace
neil

You say that you are trying to store the method body
into a database. This is to allow you to store an
object and its methods into a database. Are you trying
store the method text or its implementation (i.e class
or java). If it is the implementation then just
serialize the found method object using reflection.
WHY are you doing this ?? what about private methods,
class variables, class methods ???Hi, yes it is confusing to explain, but I'm experimenting with a new programming paradigm called AspectJ and I've only just got into Reflection. I'm creating a repository of Aspects (same as classes but with added functionality and some limitations) with JDBC and don't want to just serialise the object as a blob and so have created data tables to hold different parts of the anatomy of an Aspect and this was the only thing I was getting stuck on.
The idea is that the user is able to recall these whole aspects (or a part of them such as a method) on the fly and use them in a program. I realise that ther will be problems because these methods may have other dependencies such as the ones you explain above but its just experimental at the moment and those are the kinds of things I'm wanting to find out more.
I've seen examples of reflection for Objects but never for methods. So it is possible to capture just a method by serialisation using reflection? Any examples would be much appreciated.
Peace
Neil

Similar Messages

  • How to use reflection to get base classes protected field

    I have one base Base classes which have protected fields and public get method to get the field.
    class Base
    protected int proField;
    public int getProField(){return proField;}
    Class Derive extends base class Base
    class Derive extends Base implements OtherInterface
    public void funtion(){};
    Now I have an instance of Derive, how can I use reflection to get the protected field inherited from Base. It seems Java Reflection only give runtime accessibility to public field and decleared field, protected-inherited field is excluded.
    Thanks
    Lei

    as the last poster said, traverse up the class hierarchy.
    ex:
    private void doSumfinToField(String fieldName throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
    Class clazz = getClass();
    Field field = findFieldInClass(clazz, fieldName);
    //field.doSumfin;
    private Field findFieldInClass(Class clazz, String fieldName) throws NoSuchFieldException {
    try { // to find the field in this class    
    return clazz.getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
    // if we don't have a superclass, continue
    if (clazz.getSuperclass().equals(Object.class)) {
    throw e;
    // check in the superclass
    return findFieldInClass(clazz.getSuperclass(), fieldName);
    }

  • Using reflections for Private methods

    hi,
    I want to call a public method through reflection.
    For that the following code needs to be written:
    new java.lang.reflect.ReflectPermission("suppressAccessChecks");
    I don't know how to link this with my application.
    Can anyone help me out in this?
    Thanks
    Ankush

    I don't know what's the problem with my coding:
    OK I tell u the exact problem;
    I have 3 packages: Pkg1, pkg2, pkg3
    in each package I have many classes.
    I am following 3 tier architecture so in pkg2 class I have an instance of Pkg1 corresponding class and in pk3 class i have an instance of pkg2 corresponding class
    Now I am trying to use the following code to execute with any method in any package:
    while(stToken.hasMoreTokens())
    lsMethodName = stToken.nextToken().trim();
    if(stToken.hasMoreTokens()){
    // For tokens which is not last
    m = loObjectName.getClass().getMethod(lsMethodName,null);
    m.setAccessible(true);
    loObjectName = m.invoke(loObjectName,null);
    else {
    // For the last Token
    m = loObjectName.getClass().getMethod(lsMethodName,arr);
    m.setAccessible(true);
    loObjectName = m.invoke(loObjectName,obj);
    the methods call can be
    Pkg1InstancePkg2.pkg2Instancepkg3.Pkg3Method
    or
    gettxtWebstar.setText , here webstar is the text field
    I get error whenever I call the getDeclaredMethod on first method.
    Thanks in advance
    Ankush
         

  • Login to a website using httpURLConnection and GET methods

    Hello,
    I would like to write a java program that connects to a website, logs in by sending relevant data to the javascript I copy-pasted below and then retrieves the information of the webpage reached after successful login.
    <FORM method="post" name="loginForm" action="/cvg/dispatch/login/submit">
    <TABLE>
    <TR>
    <TD>
    <TABLE BGCOLOR=#D0E2FF WIDTH="100%" BORDER="0" CELLPADDING="3" CELLSPACING="0">
    <TR><TD COLSPAN=2>�</TD></TR>
    <TR>
    <TD ALIGN="RIGHT"><FONT SIZE=3>login</FONT></TD>
    <TD><input type="text" name="loginValues.userName" value="" size="15" maxlength="30" ><input type="hidden" name="priority-normal" value="loginValues.userName"></TD>
    </TR>
    <TR>
    <TD ALIGN="RIGHT"><FONT SIZE=3>password</FONT></TD>
    <TD><input type="password" name="loginValues.password" value="" size="15" maxlength="30" ><input type="hidden" name="priority-normal" value="loginValues.password">
    </TD>
    </TR>
    <TR>
    <TD ALIGN="CENTER" COLSPAN=2>
    <input type="image" name="Login" value="Login" src="/cvg/images/login-button.gif" alt="Login" border="0" width="67" height="33" ><input type="hidden" name="submitButton" value="Login"><input type="hidden" name="Login-action" value="Login">
    </TD>
    </TR>
    </TABLE>
    Thanks for your help

    Using POST
    http://forum.java.sun.com/thread.jspa?threadID=645830
    second POST
    Using GET
    URL u = new URL("http://server/cvg/dispatch/login/submit?loginValues.userName=user&priority-normal=loginValues.userName&loginValues.passwor=password&priority...")
    By the way the html you provided does not use GET at all, it uses POST
    <FORM method="post" ring any bell?
    As for javascript, I don't see any script on the html page you provide, nor
    do I see any onsubmit or onclick action.

  • Retrieving image using HTTP GET method?

    I want to send a image to a client browser. My servlet's HTML response to the client browser contains the <img src="..."> tag. The client browser uses the HTTP GET method to call my servlet's DoGet method, and I must transfer the desired image to the client browser in this DoGet method at servlet. Now, the problem is that, what should be the source URL in the image(img) tag that is present in my servlet response to client?
    For eg: the img tag should be like this
    <img src="http://<hostname>:<portname>/<servletname>/...?[var1=value1]">
    Now at the ellipsis that you see in the above source URI, I want to write the type of image file (something.jpg) ,so the browser knows what kind of image file it is.
    To sum it up...how to get the image using DoGet method and <img src="...">
    Regards,
    Amit

    To give you a better idea on what's happening, read the RFC:
    (HTTP/1.0) http://ftp.ics.uci.edu/pub/ietf/http/rfc1945.html
    (HTTP/1.1 - compressed data)
    http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
    If you for example execute the command by telnetting to port 80 on a server:
    GET http://somewhere.com/some.jpg HTTP/1.0<cr>
    <cr>You will get this header:
    Trying 217.22.64.73...
    Connected to xxx.xxx.xxx
    Escape character is '^]'.
    HTTP/1.1 200 OK
    Date: Fri, 01 Aug 2003 12:36:30 GMT
    Server: Apache/1.3.27 (Unix) FrontPage/5.0.2.2510
    Last-Modified: Tue, 15 Jul 2003 03:11:52 GMT
    ETag: "268de8-2fc4-3f1370f8"
    Accept-Ranges: bytes
    Content-Length: 12228
    Connection: close
    Content-Type: image/jpegWatch the last part, that's what the setContentType does, normally the content-type defaults to text/html in a webserver.
    A webserver usually maintains a list of file extensions by which it will determine the correct MIME type to emit, when a resource is retrieved.
    The browser reads the header, and decides what to do with it, in combination with (X)HTML markup.
    Greets.

  • Invoking a method using reflection with json data as argument

    Hi,
    I want to invoke a method using reflection and this method have one argument . Now I want to pass a json data as an argument to this method .Please see the following code.
    int HelloWorld(int Id){
    return Id;
    json data{"Id":43}
    how can I use the reflection to use the json.
    Please provide your guidelines

    Thanks for your reply, I am building a windows console application .And I want to convert the json data to object array to use in Method Base.Invoke method.
    Regards,
    Ethan
    Maybe you could select the correct language development forum here:
    http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?category=vslanguages&filter=alltypes&sort=lastpostdesc
    Best Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • 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)

  • Whether private getter methods is Evil?

    Hi!
    I was wondering whether it is bad or good to use private getter methods in a class rather than directly accessing private fields?
    For instance, I have a getter method for each Swig component used in my program:
        private JButton run;
        private JButton getRun() {
             if (run != null) {
                  return run;
            run = new JButton("Run");
            run.setToolTipText("Run");
            run.setIcon(new ImageIcon(ResourceHelper.getImageResource("run.png")));
            run.setEnabled(false);
            run.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    MessageDialog.showPleaseWait(TestRunnerUI.this,
                        "creating logger", new Runnable() {
                            public void run() {
    // bla bla bla
            return run;
        }And so for each swing component....
    But for example I have such a method:
        private void disconnect() {
            mRunner = null;
            mLogger = null;       
            log.log(Logger.INFO, "disconnected");
            tree.setModel(defaultModel);
            tree.setEnabled(true);
            save.setEnabled(false);
            saveAs.setEnabled(false);
            load.setEnabled(false);
            options.setEnabled(false);
            run.setEnabled(false);
            breakTests.setEnabled(false);
            connect.setEnabled(true);
            disconnect.setEnabled(false);
        }which changes properties of a lot of components...
    I don't know whether I should use there private getter methods or not. From the design perspective it seems I should but it also adds some overhead I suppose...

    I use accessor methods when writing persistent
    classes and javabeans. The key is not to use them by
    default, only when required. IMO this does not
    violate encapsulation, it hides implementation. Agree. Inside the bean itself you shouldn't use it's accessors either.
    The
    main benefit being that should you need to refactor
    the way a value is retrieved or set you have
    localized the changes. Holub will tell you that if
    you are using an accessor method to retrieve a value
    from an object, in order to do some computation on
    that value, you should move the computation into the
    object's class instead (hence "getter and setter
    methods are evil").Summarized, the public accessors are evil when the code behind does not only return/set the encapsulated value. Solution: refactor, split and rename them to "createSomething", "lookupSomething", "buildSomething", or so.
    In this case the topicstarter was talking about private getters tho.

  • Must I Use Reflection?

    Hi, i posted here this question, �cause it�s about DB and JDBC.
    I`m coding a simple visual program, to connect with JDBC.
    i have a field, who capture the path of the DB, and i need to get form there, the string:
    "sun.jdbc.odbc.JdbcOdbcDriver"
    must i use reflection to get it?
    Or there�s another way to do this?
    Thanks a lot.

    Your question makes no sense.
    The value you posted represents the name of a particular JDBC driver.
    The string itself is a string. Nothing more. Nothing less. You can get it anywhere you can get a string from. Like a text file, a properties file, a command line option, hard coded etc. Just like you can do the same with other string values.
    You certainly can't get that string from a jar file, just by itself.
    No perhaps you mean the driver itself and not the string?
    Then the answer is no - you can't get it from a "jar". That particular driver is a proprietary driver that only comes with the Sun VM (how it lives in the VM is irrelevant to the question.) And that is the only way you can use it. If you run your app in a Sun VM then it is always there. If it isn't a Sun VM then it isn't there.

  • 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.

  • How to access private method of an inner class using reflection.

    Can somebody tell me that how can i access private method of an inner class using reflection.
    There is a scenario like
    class A
    class B
    private fun() {
    now i want to use method fun() of an inner class inside third class i.e "class c".
    Can i use reflection in someway to access this private method fun() in class c.

    I suppose for unit tests, there could be cases when you need to access private methods that you don't want your real code to access.
    Reflection with inner classes can be tricky. I tried getting the constructor, but it kept failing until I saw that even though the default constructor is a no-arg, for inner classes that aren't static, apparently the constructor for the inner class itself takes an instance of the outer class as a param.
    So here's what it looks like:
            //list of inner classes, if any
            Class[] classlist = A.class.getDeclaredClasses();
            A outer = new A();
            try {
                for (int i =0; i < classlist.length; i++){
                    if (! classlist.getSimpleName().equals("B")){
    //skip other classes
    continue;
    //this is what I mention above.
    Constructor constr = classlist[i].getDeclaredConstructor(A.class);
    constr.setAccessible(true);
    Object inner = constr.newInstance(outer);
    Method meth = classlist[i].getDeclaredMethod("testMethod");
    meth.setAccessible(true);
    //the actual method call
    meth.invoke(inner);
    } catch (Exception e) {
    throw new RuntimeException(e);
    Good luck, and if you find yourself relying on this too much, it might mean a code redesign.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Getting Method objects without reflection

    This is a shameless plug to try to get votes for a recent bug I've filed:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6356762
    For a long time, it's bothered me that there is no way other than reflection to obtain Method and Field objects to identify components of classes. It should be possible to write something like MyClass.class.nameOfMyField to obtain the FIeld object directly. With the current reflection-only method, one has to obtain these by looking up their String names. So:
    -there's no way for the compiler to detect syntax errors at compile time
    -no real way to obfuscate this code
    -debugging is more difficult because you are working indirectly through strings
    -it's inelegant to use Strings to perform at runtime what the compiler should be able to do at compile time
    One of the most immediate uses for this could be with classes conforming to the Beans pattern. Instead of specifying String names directly when firing property change events (whilch always risks a typo cauing a hard to trace error), you could obtain the coresponding Field object and call getName() on it.
    If something like this could be provided in Mustang, I would be in seventh heaven. Please vote for the bug, or let me know what you think about this.

    I would definately have usage of that. I've always loved function pointers in C, and jump tables in assembler.
    Kaj

  • Reflection cant get parameterized method signature?

    my sample:
    interface Root<T>{
    public void prt(T t );
    interface A extends Root<String>{
    public class Reflecttest {
    public static void main(String[] args){
    Class cl=A.class;
    for (Method m:cl.getMethods()){
    m.getParameterTypes();
    //som reflection like above, but i cant get signature like public void prt(String str); but public void prt(Object o);
    //how can i get the parameterized method signature
    }

    That information doesn't exist at runtime. It is all
    erased to Object by the compiler. That's what
    Generics does - safe type erasurefurther, you don't need to know, since by using reflection you're basically bypassing compile-time type safety altogether. reflection and generics have totally different intents, and don't mix well together

  • Reflection: result of getting Methods

    Hi
    I'm using reflection to see what methods a class has. When I do reflection on java.awt.Button I get the same method occuring more than once. (At the moment my code is a little rough around the edges so it might just be my code.) My Question: Do all overriden (potentially abstract) methods get listed by getMethods(). If this is the case which one of the two (or more) methods do I call invoke on?

    Methods in Java can be overridden and overloaded. Overloaded methods are distinguished by their signature, that is basically the list of parameters that a method is passed including the null or empty list.
    Overridden methods are methods which override a method from an inherited class.
    To query a class for locally declared methods you need to call getDeclaredMethods. The returns an array of Method objects for all methods declared specifically by the queried class.
    To query a class about ALL publicly declared methods then you call getMethods, this method returns an array of Method instances that are exposed by the class in question and ALL inherited classes.
    API information about querying a class for its properties can be found in the JavaDocs for java.lang.Class.
    The Method class has methods which are useful in determining things like access modifiers, thrown exceptions, parameter list etc.
    API information about Reflection and things like the Method class can be in the JavaDocs for java.lang.reflect package.
    It is also worth looking at the java.beans package(s) in detail as well, there are things in there that can of great use to you when dealing with Reflection and Introspection.

Maybe you are looking for