Specific class methods via reflection?

I need to get the methods of a class, but not the methods that are inherited by the class, but just those implemented in the actual class.
I tried this way:
public class MethodsTest {
    private int prim;
    private String joc;
    public String getJoc() {
        return joc;
    public void setJoc(String joc) {
        this.joc = joc;
    public int getPrim() {
        return prim;
    public void setPrim(int prim) {
        this.prim = prim;
    public static void main(String[] args) {
        // get the methods
        MethodsTest mt = new MethodsTest();
        Class clz = mt.getClass();
        Method[] mtz = clz.getMethods();
        System.out.println(Arrays.toString(mtz));
        // it prints all methods.
}but it prints all methods, from this class and from the superclasses:
[public java.lang.String com.datamedical.testes.xml.MethodsTest.getJoc(),
public void com.datamedical.testes.xml.MethodsTest.setJoc(java.lang.String),
public int com.datamedical.testes.xml.MethodsTest.getPrim(),
public void com.datamedical.testes.xml.MethodsTest.setPrim(int),
public static void com.datamedical.testes.xml.MethodsTest.main(java.lang.String[]),
public native int java.lang.Object.hashCode(),
public final native java.lang.Class java.lang.Object.getClass(),
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException,
public final void java.lang.Object.wait() throws java.lang.InterruptedException,
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException,
public boolean java.lang.Object.equals(java.lang.Object),
public java.lang.String java.lang.Object.toString(),
public final native void java.lang.Object.notify(),
public final native void java.lang.Object.notifyAll()]

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getDeclaredMethods()

Similar Messages

  • Set fields of derived class in base class constructor via reflection?

    Does the Java Language Specification explicitly allow setting of fields of a derived class from within the base class' constructor via reflection? The following test case runs green, but I would really like to know if this Java code is compatible among different VM implementations.
    Many thanks for your feedback!
    Norman
    public class DerivedClassReflectionWorksInBaseClassConstructorTest extends TestCase {
    abstract static class A {
        A() {
            try {
                getClass().getDeclaredField("x").setInt(this, 42);
            } catch (Exception e) {
                throw new RuntimeException(e);
    static class B extends A {
        int x;
        B() {
        B(int x) {
            this.x = x;
    public void testThatItWorks() {
        assertEquals(42, new B().x);
        assertEquals(99, new B(99).x);
    }

    why not just put a method in the superclass that the subclasses can call to initialize the subclass member variable?In derived classes (which are plug-ins), clients can use a field annotation which provides some parameter metadata such as validators and the default value. The framework must set the default value of fields, before the class' initializer or constructors are called. If the framework would do this after derived class' initializer or constructors are called, they would be overwritten:
    Framework:
    public abstract class Operator {
        public abstract void initialize();
    }Plug-In:
    public class SomeOperator extends Operator {
        @Parameter(defaultValue="42", interval="[0,100)")
        double threshold;
        @Parameter(defaultValue="C", valueSet="A,B,C")
        String mode;
        public void setThreshold(double threshold) {this.threshold = threshold;}
        public void setMode(String mode) {this.mode = mode;}
        // called by the framework after default values have been set
        public void initialize() {
    }On the other hand, the default values and other metadata are also used to create GUIs and XML I/O for the derived operator class, without having it instantiated. So we cannot use the initial instance field values for that, because we don't have an instance.

  • Calling EJB facades via class instantiated via reflection?

    We are loading plugins via Java reflection. Anything instantiated via newInstance() does not appear to have access to the Local interface.
    Right now, to get to the session bean we must use the Remote interface. This is annoying due to the performance, and seems completely unnecessary when everything is operating in one JVM.
    Tests were done to print out the JNDI namespace and the local interfaces don't seem to be accessible. Any advice?

    My project consists of an EJB package and WAR. I have not had any problem calling the local facades from JSP, Servlet, or web service in the EJB package.
    Further, I can use XStream reflection and do local EJB calls.
    It baffles me why I can't do the local calls in some classes via InitialContext lookups.
    I will post test code next week.

  • Execute specific class/method in jar

    Hi!
    Is there any way to execute a particular main method of a class inside a jar-file? I have several main-methods that I would like to run, something like this:
    java -jar my.jar classA
    java -jar my.jar classB
    but I find no way of doing it. Is it possible?

    I thought so to. It doesn't. It says
    "NoClassDefFoundError: "I am assuming the class that isn't found is one of the main classes. Either the class is not in the jar, the class is not correctly installed into the jar, or you did not correctlys specify the class.
    For example, if the classes are in package yourpack and are named Main1 and Main2, they must be in the jar as yourpack/Main1 and yourpack/Main2. You must specify them as in
    java -classpath path/to/thejar.jar yourpack.Main1

  • Class Methods throught Reflect

    Is it necessary to execute the Class.getMethods() method to retrieve the methods with a certain name?
    For example :
    public class XPTO{
    public void test(int i){}
    public void test(String str){}
    public void test(long l){}
    }I just need the test methods, but the getMethods() returns besides the looked for methods, also the inhereted methods and other defined methods in the actual Class.
    In this case the class just has a couple of methods, now lets imagine a javax.swing.JComponent subclass... with more implemented methods in it.
    Well you may say it fast to process a search, or filter for the methods, but lets imagine that it's necessary to process this type of action for thousands of Class's (a little extremist?!? Maybe).
    Daniel Campelo

    then there is no other way than going through all
    methods, unless those methods are part of a certain
    (smaller) interface or are being declared in a known
    class, in which case you could use
    getDeclaredMethods() of that certain class.In the given example i was searching for methods that were defined in the processed class but there can be methods defined in the super class...And the intention is to retreave all methods that correspond to a given name that a certain class has defined (or it's super class's).
    however, I don't think that going through all method
    names will be a bottleneck for your application...It may be true for a couple of class's with not many methods defined but like i said : '(...)lets imagine that it's necessary to process this type of action for thousands of Class's(...)'.
    Many milliseconds make seconds that in turn make minutes and so on...
    I'll teste it and will report back...
    Thanx for the help so far :)
    Daniel Campelo

  • How to load a class dynamically (via reflection) in a jsf-component

    Hi all,
    I am writing my own jsf component and I would like to do it generically. Therefore I have an attribute, where the developer can pass a fully qualified classname, which I want to use to instantiate. But I have a Problem with the classloaders, everytime I get a ClassNotFound-Exception during debugging.
    Does anybody know how it is possible, to to get the most parent classloader?
    Currently I am even not able to load a class, which is in the same package like all other compontent-classes.
    Thank you very much in advance
    Thomas

    Within web applications, I believe it is recommended to use Thread.getContextClassLoader(). Keep in mind that web applications require different classloader semantics than regular Java applications. The class loader which gets resources from the WAR is favored over others, even when this violates the normal class loading conventions.

  • Class loading and reflection

    Hi,
    I am trying to use a custom class loader to dynamically load Java classes so that I can get some info (e.g. methods) about the classes via reflection. My problem is that my class loader is written to load Java core classes (i.e. java.lang, java.util, etc.), which as far as I know cannot be done since ClassLoader.defineClass() disallows such attempts. The reason I need to load the core classes is because my program extensively uses Java 5 features (thus have to run using JRE version 5) but need access to Java 1.4 classes in order to get the class' info via reflection.
    I am almost out of ideas and thought that what I am trying to do might be achievable if there is a way where I can use the reflection APIs without loading a class first -- I doubt that this can be done using standard Java API, but I will appreciate it if anyone knows any tools/libraries that can do this or if anyone can give other suggestions to solve my problem.
    Thanks,
    Hendrik

    slackiz wrote:
    Hi,
    I am trying to use a custom class loader to dynamically load Java classes so that I can get some info (e.g. methods) about the classes via reflection. My problem is that my class loader is written to load Java core classes (i.e. java.lang, java.util, etc.), which as far as I know cannot be done since ClassLoader.defineClass() disallows such attempts. The reason I need to load the core classes is because my program extensively uses Java 5 features (thus have to run using JRE version 5) but need access to Java 1.4 classes in order to get the class' info via reflection.
    Just to be clear in case someone else in the future finds this....
    You cannot and must not attempt to "load" core classes from different VM versions into the same VM.
    It doesn't matter what the reason is it is will always be wrong.
    Conversely I am guessing the OP just wants to look/interpret the classes versus actually loading them. So BCEL should work or one could always roll their own class file reader.

  • Invoking private methods by reflection........

    Hi,
    Iam trying to invoke a private method of an object of some class thru reflection. Despite setting method.setAccessible( true), Iam not able to invoke the private method. Is invoking private methods via reflection not allowed at all?
    thanks,

    This worked for me :
    public class Test {
         public static void main(String[] arg) throws Exception {
              TestAccess t = new TestAccess();
              Method m = t.getClass().getDeclaredMethod("foo", null);
              m.setAccessible(true);
              m.invoke(t, null);
    class TestAccess {
         private void foo() {
              System.out.println("This is private");
    }

  • Invoking methods through reflection

    I need to check a property in the javax.faces.component.html.HtmlInputText.
    If i do it in the following manner,I get things fine:
    if(comp.getClass().getName().equalsIgnoreCase("javax.faces.component.html.HtmlInputText")) {
    String getter=((javax.faces.component.html.HtmlInputText)comp).getOnfocus();
    if(getter!=null) {
    System.out.println(getter);
    But if i invoke it through reflection,I get nothing.
    I am doing the following:
    Class reqClass = Class.forName("javax.faces.component.html.HtmlInputText");
    Method[] methodList = reqClass.getDeclaredMethods();
    int methodIdx = 0;
    for (int i = 0; i < methodList.length; i++) {
    Method reqMethod =methodList;
    if(reqMethod.getName().indexOf("getOn")== 0) //method starts with getOn
    // method accepts parameters, define the types in order here as Class[]
    Class[] classParams = new Class [] {};
    // set the method of the class object
    Method method = reqClass.getMethod( reqMethod.getName(), classParams );
    // pass values to fill parameters of method
    Object[] arguments = new Object [] {};
    // invoke method via reflection.Note that class has default constructor
    Object retobj=method.invoke( reqClass.newInstance() ,
    arguments );
    String getterResult = (String)retobj;
    if(getterResult!=null)
    System.out.println(reqMethod.getName() + " ## " + getterResult);
    What am i doing wrong while invoking the method through reflection.
    I get no exception either.

    It is a simple typo.
    An alternative I tried is the following ,but that does not work either.
    Class reqClass = Class.forName("javax.faces.component.html.HtmlInputText");
    Method[] methodList = reqClass.getDeclaredMethods();
    int methodIdx = 0;
    for (int i = 0; i < methodList.length; i++) {
    Method reqMethod =methodList;
    if(reqMethod.getName().startsWith("getOn")) //method starts with getOn
    System.out.println(reqMethod.getName());
    // pass values to fill parameters of method
    Object[] arguments = new Object [] {};
    // invoke method via reflection
    Object retobj=reqMethod.invoke( reqClass.newInstance(), arguments );
    String getterResult = (String)retobj;
    if(getterResult!=null)
    System.out.println(reqMethod.getName() + " ## " +getterResult);

  • Loading a class via reflection without knowing the full qualified path ?

    Hi there
    I d like to load a class via reflection and call the constructor of the class object. My problem is that I dont know the full qulified name e.g. org.xyz.Classname bur only the Classname.
    I tried different things but none seem to work:
         1. Class c = Class.forName("Classname");  //does not suffice, full qualified name required
    2. ClassLoader classloader = java.lang.ClassLoader.getSystemClassLoader();
             try {
               Class cl = classloader.loadClass(stripFileType(Filename));//if i do not pass the full qualified name i get a ClassNotFoundException
    3. I tried to consruct a class object with my own classloader , calling:
              Class cl = super.defineClass(null, b, 0, b.length );     b is of type byte[]This almost works. I get a class Object without knowing the full qulified path. I can transform a filename into a raw array of bytes and I get the class out of it. But there is still a problem: If there are more than on classes defined in the same textfile I get an InvocationTargetException.
    It looks like this:
    package org.eml.adaptiveUI.demo;
    import com.borland.jbcl.layout.*;
    import java.awt.*;
    import org.eml.adaptiveUI.layout.*;
    import javax.swing.*;
    import java.awt.event.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2003</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class twoButtons extends JFrame {
      SPanel sPanel1 = new SPanel();
      JButton jButton1 = new JButton();
      GridBagLayout gridBagLayout1 = new GridBagLayout();
      GridBagLayout gridBagLayout2 = new GridBagLayout();
      public twoButtons() throws HeadlessException {
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      public static void main(String args[]){
        twoButtons twob = new twoButtons();
        twob.pack();
        twob.show();
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(gridBagLayout1);
        jButton1.setText("button 1");
        jButton1.addActionListener(new TransformationDemo_jButton1_actionAdapter(this));
        this.getContentPane().add(sPanel1,  new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
                ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(57, 52, 94, 108), 35, 44));
        sPanel1.add(jButton1,  new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
                ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 41, 0, 0), 0, 0));
      void jButton1_actionPerformed(ActionEvent e) {
        System.out.println("button 1 source: " + e.getSource());
        System.out.println("d: " + e.getID());
       System.out.println("/n commmand: " + e.getActionCommand());
    class TransformationDemo_jButton1_actionAdapter implements java.awt.event.ActionListener {
      twoButtons adaptee;
      TransformationDemo_jButton1_actionAdapter(twoButtons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton1_actionPerformed(e);
    }As you can see there is the class TransformationDemo_jButton1_actionAdapter class defined in the same classfile. The problem is now that the twoButtons constructor calls the TransfomationDemo_jButton1_actionAdapter constructor and this leads to InvocationTargetException. I dont know if this is a java bug because it should be possible.
    Can you help me?

    hi thanks at first,
    the thing you mentioned could be a problem, but I dont think it is.
    If I have the full qualified name (which I havent) then everything goes normal. I only have to load the "twoButtons" class and not the other (actionadapter class), so I dont think this is the point. In this case the twoButtons constructor constructs an object of the actionadapter class and everything goes well. The bad thing is though that I do not have the full qulified name :(
    Invocation target exception tells me (in own words): Tried to acces the constructor of the actionadapter class (which is not public) out of class reflectionTest class .
    reflectionTest is the class where the reflection stuff happens and the twoButttons class is defineClass() ed.
    The problem is, only twoButtons class has the rights to call methods from the actionadapter class, the reflection class does not. BUT: I do not call the actionadapter methods from the reflection class. I call them only from the twoButtons class.
    I hope somebody understands my problem :)

  • How to instantiate class via reflection

    Hi, I want to generically instatiate classes, but obviously Class.newInstance only works if the class has a public no args constructor. Is there any way to instantiate classes without such a constructor via reflection? It would be sufficient for me if I could use a private no args constructor.
    I already tried the following:
    Class clazz = Class.forName( "classname" );
    Constructor constructor =
    clazz.getDeclaredConstructor( new Class[] { } );
    constructor.setAccessible( true );
    object = constructor.newInstance( new Object[] {} );
    But it, too, yielded to an IllegalAccessException.

    Class clazz = Class.forName( "classname" );
    Constructor constructor =
    clazz.getDeclaredConstructor( new Class[] { } );
    constructor.setAccessible( true );
    object = constructor.newInstance( new Object[] {} );
    But it, too, yielded to an IllegalAccessException.constructor.setAccessible( true );
    is the call that generates the IllegalAccessException. Your code must be allowed to supress access checks. This is always the case if you don't have a security manager, otherwise the security manger's checkPermission method is called with an ReflectPermission("supressAccessChecks") argument.
    Either that or the getDeclaredConstructor throws the exception, in that case your code must be allowed to "check member access".
    Hope it helped,
    Daniel

  • Need to send the remittane advices via e-mail for specific payment method

    Hi,
    I need to genrate and send payment advices to vendors via e-mail for the specific payment method and specific currency.
    I have to send the payment summary and DME Accompaying sheet via e-mail to the vendors. And if no e-mail exists for vendors the system should generate a spool to request print those.
    VS Kumar

    Hi Sateesh,
    You need to copy SAMPLE_PROCESS_00002040 and adjust it to write code as per your requirement. This BTE runs for each payment advice note to be sent and in the module, it is mentioned 1=print, 2 = Fax and I=mail, so you can set your priority, that if an E-Mail address is maintained in the vendor master, send mail or if no E-mail address is maintained shoot a Print.
    From Configuration side, you need to maintain the Z copy of SAMPLE_PROCESS_00002040 in FIBF transaction under the Process module of a customer without country or application indicator. 
    Refer to SAP Note 836169 - Consulting: Payment advice notes by email or fax.                                                                       
    Regards,
    SAPFICO

  • Best Practice for Updating Infotype HRP1001 via Class / Methods

    I want to update an existing (custom) relationship between two positions.
    For example I want
    Position 1 S  = '50007200'
    Position 2 S =  '50007202'
    Relationship = 'AZCR'
    effective today through 99991231
    Is there a best practice or generally accepted way for doing this using classes/methods rather than RH_INSERT_INFTY ?
    If so, please supply an example.
    Thanks...
    ....Mike

    Hi Scott
    You can use a BAPI to do that.
    Check the following thread:
    BAPI to update characteristics in Material master?
    BR
    Caetano

  • Setting Fields value via reflection

    I'm starting from a c# code:
              internal void RefreshFromObject(object objFromUpdate)
                   if (this.GetType()==objFromUpdate.GetType())
                        PropertyInfo[] fieldsFrom = objFromUpdate.GetType().GetProperties();
                        PropertyInfo[] fieldsThis = this.GetType().GetProperties();
                        for(int idxProp=0; idxProp<fieldsFrom.Length;idxProp++)
                             if (fieldsThis[idxProp].CanWrite && fieldsFrom[idxProp].CanRead)
                                  fieldsThis[idxProp].SetValue(this, fieldsFrom[idxProp].GetValue(objFromUpdate,null),null);
                   else
                        throw new ObjectTypeNotValidException("Object type from which update current instance not valid. Use same type.");
    Now I have to translate it in Java:
    Class clazz = objFromUpdate.getClass();
    Class thisClazz = this.getClass();
    do {
         Field[] fieldsFrom = clazz.getDeclaredFields();
         Field[] fieldsThis = thisClazz.getDeclaredFields();
         try {
              fieldsThis[idxProp].set(thisClazz, fieldsFrom[idxProp].get(clazz));
         catch (IllegalAccessException iaccEx) {
              System.out.println("IllegalAccessException");
         catch (IllegalArgumentException iaccEx) {
              System.out.println("IllegalArgumentException");
    clazz = clazz.getSuperclass();
    thisClazz = thisClazz.getSuperclass();
    } while (clazz != null && clazz != Object.class);
    My problem is that I don't know if the field type is one of primitive, for which I should use the particular setters and getters.
    My questions are:
    1) is there in Java a more elegant way to set fields values via reflection?
    2) how can I know if a field i changable (equivalent to the method CanWrite of c#?
    Thanks a lot to each one that will answer me.
    Marco

    Hi georgemc,
    thanks for replying. I-m new with java forum, so I don't know if it is correct the code tags...
    Anyway... the problem is that the Field of reflected object could be both of Object types or primitive types. So I cannot use the general method "set" when changing Field's value.
    Maybe somebody else had the same problem...
    Seems in C# it is a very easy thing... not in java :(
    Marco
    Class clazz = objFromUpdate.getClass();
    Class thisClazz = this.getClass();
    do {
    Field[] fieldsFrom = clazz.getDeclaredFields();
    Field[] fieldsThis = thisClazz.getDeclaredFields();
    try {
    fieldsThis[idxProp].set(thisClazz, fieldsFrom[idxProp].get(clazz));
    catch (IllegalAccessException iaccEx) {
    System.out.println("IllegalAccessException");
    catch (IllegalArgumentException iaccEx) {
    System.out.println("IllegalArgumentException");
    clazz = clazz.getSuperclass();
    thisClazz = thisClazz.getSuperclass();
    } while (clazz != null && clazz != Object.class);

  • Generics via reflection and newInstance()

    I'm looking for a way, or a correct syntax, for 'genericizing' the
    class instantiation via Class#newInstance() method using reflection.
    The code shown below is an half-baked solution in that compiler emits
    unchecked cast warning against the cast on the 'obj' variable at the
    last part of the code.
    I think I have tried everyting conceivable for Class variable declarations
    and other part of the code but they were all futile. I lost one night
    sleep for that.
    If there are Java Generics gurus on the forum, please help!
    TIA.
    import java.util.*;
    import java.lang.reflect.*;
    public class GetMethod{
      public static void main(String[] args) {
        Object obj = null;
        Class<Hashtable> clazz = Hashtable.class;
        Class<Class> claxx = Class.class;
        try {
          Method method = claxx.getMethod("newInstance");
          obj = method.invoke(clazz);
        catch (Exception e) {
          e.printStackTrace();
        Hashtable<String,String> ht = (Hashtable<String,String>)obj;
        ht.put("foo", "bar");
        System.out.println(ht.get("foo"));
    }

    If you are preparing teaching material, then I would strongly suggest that you do not mix generics with reflection until both are very well understood.
    Using reflection to invoke reflection API methods (or any method known at compile time) as you did in your example, suggests that you do not understand enough yet.
    Because generics are a compile time mechanism and reflection is run time, many of the naive assumptions you might make just wont hold. Reflection is a mechanism for subverting the compiler, don't expect reflection and the compiler to have a harmonious relationship.
    Please remember when writing training material, that the code you use will be assumed by your students to be the best way to solve the problem it purports to solve. You need to bear this in mind when choosing code samples, not only must the sample illustrate the feature being taught, but it must be an appropriate application of that feature. If you do not choose appropriate problems to solve with your illustrative code, you will unwittingly train a generation of incompetents, whose code will be even stupider than yours.
    Bruce

Maybe you are looking for

  • CS4 Bridge - Black stroke around image in Web Gallery

    More specifically, I'm using the LightRoom Flash Gallery selection as that provides just the structure that I want/need. To match my website (still in construction) I've altered the colors in Bridge's controls. Separately, I've added a frame around e

  • Gmail - Username and password do not match Options

    I get this message every time I try to log into my Gmail account on my new iPod Touch, although the same username and password allow me to log in on my laptop. I know I'm using the correct username and password, but If I go to the relevant link via m

  • Problem in text processing

    Hi, I made a program that makes a lot of processing and when i compile it no error appears but a warning happens. The warning is: ResultServlet.java uses unchecked or unsafe operations What exactly is the source of this warning. Thanks.

  • Why do we need the @EJB annotation at the class level?

    Why do we need the @EJB annotation at the class level? Eg: Why do we need the first piece of code, when the second code seems much simpler . *1.* @Stateful @EJB(name="ejb/TradeLocalNm", beanInterface=TradeLocal.class) public class TradeClientBean imp

  • 2 identical Strings won't match?

    hi, i have a program that takes some bytes out of a data file. It then checks to see if the data matches the requested IDs. I have a strange problem. I have 2 different IDs that i have requested. When I request the first, it works fine and the progra