How to access a method of a class which just known class name as String

Hi,
Now I have several class and I want to access the method of these class. But what I have is a String which contain the complete name of the class.
For example, I have two class name class1and class2, there are method getValue in each class. Now I have a String containing one class name of these two class. I want to access the method and get the return value.
How could I do?
With Class.forName().newInstance I can get a Object. but it doesn't help to access and execute the method I want .
Could anybody help me?
Thanks

Or, if Class1 and Class2 have a common parent class or interface (and they should if you're handling them the same way in the same codepath)...Class c = Class.forName("ClassName");
Object o = c.newInstance(); // assumes there's a public no-arg constructor
ParentClassOrInterface pcoi = (ParentClassOrInterface)o;
Something result = pcoi.someMethod(); Or, if you're on 5.0, I think generics let you do it this way: Class<ParentClassOrInterface> c = Class.forName("ClassName");
// or maybe
Class<C extends ParentClassOrInterface> c = Class.forName("ClassName");
ParentClassOrInterface pcoi = c.newInstance();
Something result = pcoi.someMethod();

Similar Messages

  • How to access java method in JSP

    Hi all,
    I need to access java class (abstract portal component) method doContent() in a JSP which is under PORTAL-INF/jsp folder.
    I did
    <%@ page import = "com.mycompany.Aclass" %>
    <%com.mycompany.Aclass a = new com.mycompany.Aclass (); %>
    Aclass is coming as autofill/prepopulated with cntrl+space
    Till this time, it is working. no errors. But when I do
    a.
    a. (a dot) no methods are populating (autofill..cntrl+space) or If I forcebly add method a.doContent(req,res)... at runtime its giving error.
    It's not only with doContent method... Its with any simple methods in that class or any other class.
    (Other than doContent method in the APC java class are prepopulating/autofilling but giving error in runtime)
    Can anyone help me... how to access java method in JSP.
    I already gone through many SDN forum post... and implemented too---but no use I refered below forum thread
    Retrieve values from Java class to JSP
    URGENT! How to call a java class from JSP.
    Calling a java method from jsp file -
    this thread is same as my issue
    Thanks,
    PradeeP

    1st. The classes must be in packages. 2nd, the package that they are in must be under the WEB-INF/classes directory. 3rd Look on google and/or this site for web application deployment

  • How to access a method in webservice catalogued component in BPM Process

    Hi
    Can anyone explain me how to access a method in webservice catalogued component in BPM Process using an imported jsp in bpm process.
    Thanks & Regards
    Ashish

    If Class B only has a reference to an Interface A, and that reference points to a concrete instance of Class A, then of course Class B can still call the method on Interface A. The method for concrete instance Class A is called behind the scenes.
    That's how interfaces work. That's what they're good for.
    Look at the code in the java.sql package for examples. Connection, Statement, ResultSet - all are interfaces. But behind the scenes you're using the concrete implementations provided by your JDBC driver. You don't know or care what those classes are or their package structure. All you do is make calls to the java.sql interface API, and it all works. - MOD

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

  • How can i access the methods if i only got the java class file?

    just like what the topic said...i would like to ask if i only got the class file of java without API documentation. how can i know what method is included ?
    thanks a lot.
    my email address is : [email protected]

    Class.getMethods()
    throws SecurityException
    Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and and those inherited from superclasses and superinterfaces. The elements in the array returned are not sorted and are not in any particular order. This method returns an array of length 0 if this Class object represents a class or interface that has no public member methods, or if this Class object represents an array class, primitive type, or void.

  • How to Access Protected Method of a Class

    Hi,
         I need to access a Protected method (ADOPT_LAYOUT) of class CL_REIS_VIEW_DEFAULT.
    If i try to call that method by using class Instance it is giving error as no access to protected class. Is there any other way to access it..

    Hi,
        You can create a sub-class of this class CL_REIS_VIEW_DEFAULT, add a new method which is in public section and call the method ADOPT_LAYOUT of the super-class in the new method. Now you can create an instance of the sub-class and call the new sub-class method.
    REPORT  ZCD_TEST.
    class sub_class definition inheriting from CL_REIS_VIEW_DEFAULT.
    public section.
      methods: meth1 changing cs_layout type LVC_S_LAYO.
    endclass.
    class sub_class implementation.
    method meth1.
      call method ADOPT_LAYOUT changing CS_LAYOUT = cs_layout.
    endmethod.
    endclass.
    data: cref type ref to sub_class.
    data: v_layout type LVC_S_LAYO.
    start-of-selection.
    create object cref.
    call method cref->meth1 changing cs_layout = v_layout.

  • How to ivoke a method on an object of a private class

    When I did it I got a java.lang.IllegalAccessException.

    Well 'private' does have a well-known meaning in
    Java, and it's been working in Java for at least 11
    years. Surely you knew that?The combination "private class" seemed unusual
    and made me de-focus from the rest of it.
    Re your example, special rules apply to inner
    classes. The access modifiers aren't tested by the
    enclosing class.Yes. The only way I am aware of of having a "private class" (as the subject implies) is to have a nested class.
    I agree one would be able to access methods on an instance of such a class only from the embedding class (or peer nested classes).

  • How to access the images stored in folder which is kept inside theapplicati

    Iam new to java..
    I want to display the images (.jpeg,,.gif, flash) which are kept in one folder
    Using Jsp...
    Its Executing fine in local system..
    Its not working 1)when i execute that jsp from other system
    2)if i give the full url then only its executing in local system
    Please help me...
    thanks in advance...
    by Priya
    <%@ page import="java.io.*"%>
    <html>
    <head>
    <title>Movie Details</title>
    </head>
    <body text="#000000" bgcolor="#FFFFFF">
    <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#FFFFFF" width="100%" id="AutoNumber1">
    <%
    File f=new File("..E:\application\Images");
    File []f2=f.listFiles();
    for(int ii=0;ii<f2.length;ii++)
    if(f2[ii].isFile())
    String fname=f2[ii].getPath();
    %>
    <tr>
    <td width="87%"><%=fname%> </td>
    <td width="14%"><img border="0" src="<%=fname%>" width="150" height="100" ></td>
    </tr>
    <%
    System.out.println(f2[ii].getPath());
    %>
    </table>
    </body>
    </html>

    Hi,
    Well i guess a Simple concept of a image servlet can cater your requirement here.
    checkout the below example of how to do it
    Configurations needed in /WEB-INF/web.xml:
    <servlet>
        <servlet-name>ImageServlet</servlet-name>
        <servlet-class>com.ImageServlet</servlet-class>
        <init-param>
           <param-name>backupFolderPath</param-name>
           <param-value>E:/application/Images</param-name>
           <!--Could use any backup folder Available on your Server and make sure we place a image file named noImage.gif which indicates that there is no file as such-->
        </init-param>
         <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DownloadServlet</servlet-name>
        <url-pattern>/Image</url-pattern>
    </servlet-mapping>
    ImageServlet.java:
    package com;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    *@Author RaHuL
    /**Image Servlet
    *  which could be accessed Image?fid=fileName
    *  or
    *  http://HOST_NAME:APPLN_PORT/ApplnContext/Image?fid=fileName
    public class DownloadServlet extends HttpServlet{
      private static String filePath = new String();
      private static boolean dirExists = false;
      public void init(ServletConfig config){
          // Acquiring Backup Folder Part
          filePath = config.getInitParameter("backupFolderPath");
          dirExists = new File(filePath).exists();      
      private void processAction(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
           // getting fileName which user is requesting for
           String fileName = request.getParameter("fid");
           //Building the filePath
           StringBuffer  tFile = new StringBuffer();
           tFile.append(filePath);    
           tFile.append(fileName); 
           boolean exists = new File(tFile.toString()).exists();
           FileInputStream input = null;
           BufferedOutputStream output = null; 
           int contentLength = 0;
           // Checking whether the file Exists or not      
           if(exists){                  
            try{
                // Getting the Mime-Type
                String contentType = this.getContentType(tFile.toString());          
                input = new FileInputStream(tFile.toString());
                contentLength = input.available();
                response.setContentType(contentType);
                response.setContentLength(contentLength);
                 String contentDispo = "";
                  try{
                     contentDispo = request.getParameter("coid");
                  }catch(Exception exp){
                 if(contentDispo != null && contentDispo.equals("69125"))
                   response.setHeader("Content-Disposition","attachment;filename=\""+fileName+"\"");       
                this.exportFile(input,response.getOutputStream());
             }catch(Exception exp){
                 exp.printStackTrace();
                 this.getServletContext().log("Exception Occured:"+exp.getMessage());
                 throw new ServletException(exp.getMessage());
           }else{
              try{
                 // Getting the Mime-Type
                String contentType = this.getContentType(filePath+"noImage.gif");          
                input = new FileInputStream(filePath+"noImage.gif");
                contentLength = input.available();
                response.setContentType(contentType);
                response.setContentLength(contentLength);
                this.exportFile(input,response.getOutputStream());
              }catch(Exception exp){
                 exp.printStackTrace();
                 this.getServletContext().log("Exception Occured:"+exp.getMessage());
                 throw new ServletException(exp.getMessage());
      /** Gets the appropriate ContentType of the File*/
      private String getContentType(String fileName){
            String url = java.net.URLConnection.guessContentTypeFromName(fileName);
               if(url == null)
                 return "application/octet-stream";
               else
                 return url;
           or one may use
           return new  javax.activation.MimetypesFileTypeMap().getContentType(fileName);
           NOTE: Do not forget to add activation.jar file in the classpath
      /** Prints the Image Response on the Output Stream*/
      private void exportFile(InputStream input,OutputStream out) throws ServletException,IOException{
             try{
                    output = new BufferedOutputStream(out);
                    while ( contentLength-- > 0 ) {
                       output.write(input.read());
                    output.flush();
              }catch(IOException e) {
                    e.printStackTrace();
                     this.getServletContext().log("Exception Occured:"+e.getMessage());
                     throw new IOException(e.getMessage());
              } finally {
                   if (output != null) {
                       try {
                          output.close();
                      } catch (IOException ie) {                     
                            ie.printStackTrace();
                         this.getServletContext().log("Exception Occured:"+e.getMessage());
                         throw new IOException(ie.getMessage());
      /** HttpServlet.doGet(request,response) Method*/
      public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{       
            // Calling  respective Action Method to Provide File Service
            this.processAction(request,response); 
      /** HttpServlet.doPost(request,response) Method*/
      public void doGet(HttpServletRequest request,HttpServletResponse response) throws         ServletException,IOException{
            // Calling  respective Action Method to Provide File Service
            this.processAction(request,response); 
    NOTE: The following code could be used to provide service to stream any sort of files with any sort of content
    with some minor modications.
    Inorder to access all the images you can restructure your jsp like the one below
    JSP:
    <!--
         And say we have are storing Image name & Movie details in the database and we are created a collection
         of all the database results like bean here is how we would display all the details with images
         Say you wrote a query to findout Moviename,timings,Hall Number & pictureFileName
         example:
            Movie: DIE HARD 4.0
            Timings: 10:00AM,2:00PM,9:15PM
            Hall NUmbers: 1,1,2,4 
            pictureFileName: die_hard_4.jpg
             or
            Movie: Transformers
            Timings: 11:20AM,2:20PM,10:15PM
            Hall NUmbers: 2,3,1,5 
            pictureFileName: transformers.jpg
         say you are saving the information in a dtoBean with properties like
          public class MovieBean{
             private String movieName;
             private String timings;
             private String pictureFileName;
             /* and followed by getters & setter of all those*/
          and say we have queried the database and finally collected an ArrayList<MovieBean> from the query results and
          saving it within the scope of session with the attribute name "MovieList"
    -->
    <%@ page language="java"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
    <html>
    <head>
    <title>Movie Details</title>
    </head>
    <body text="#000000" bgcolor="#FFFFFF">
    <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#FFFFFF" width="100%" id="AutoNumber1">
    <thead>
    <tr>
        <td>Movie Name</td>
        <td>Timings</td>
        <td>Hall Numbers</td>
        <td>Poster</td>
    </tr>
    </thead>
    <tbody>
    <c:forEach var="movieBean" items="${sessionScope.MovieList}">
        <tr>
             <td><c:out value="${movieBean.movieName}"/></td>
             <td><c:out value="${movieBean.timings}"/></td>
             <td><c:out value="${movieBean.hallNo}"/></td>
             <!-- Here is where we are making use of image servlet and trying to retrive images -->
             <td><img src="Image?fid=<c:out value="${movieBean.pictureFileName}"/>" align="center" width="30" height="30"/></td>
        </tr> 
    </c:forEach>
    </tbody>
    </table>
    </body>
    </html>Hope this might help,If that does do not forget to assign the duke stars which you promised :)
    REGARDS,
    RaHuL

  • How to access a value from "List of Values" by giving a name?

    I have a "List Of Values" defined in my BI Report. It comprises list of label-value pairs.
    I have defined a parameter :p_Value for the above "List Of Values" defnition. this parameter is used in datasource sql defnition to filter the query results. I configured a template which has a table that shows all the parameters used for filtering query results. If I give <?$p_Value?> in the template then the parameter value is rendered on it. But I want the "name" of the parameter and not the value. Can anybody tell me how to access name of the parameter which refers to one of value in "List of Value" defnition?

    option 1:
    Can you get the value from the DB in the report sql ?
    You have the code, inside the report query, if you can get the decoded value form that
    option2:
    create another paramater, LOV and query, and make it as hidden, and use the first :param_1_value in the lov query in the second param and decode the value.
    Now , you can refer the :PARAM_2_value in template which will have decoded value.

  • How to create Gantt Chart by Java? which package n class include it?

    may i know how to craete Gantt Chart or any other chart using Java programming?? which package n class enable me to do so..?? i try 2 find on API but fail lo
    thanks

    http://www.egantt.com/

  • How to get fully qualified name for a class with just the class name

    I want to get the fully qualified name of the class at runtime. The only piece of information which I have is the class name.
    I want to create a runtime instance of a class with the class name [Just the class name].
    Is there is any way to achieve this using ClassLoader?
    Could anyone suggest me an idea?
    Cheers,
    Vinn.

    Nope. If you are given "List", will you decide that means "java.util.List" or "java.awt.List"? Of course you could prompt the user to make the decision for you, I suppose. But using a class loader isn't going to make the task any easier.

  • Public class or just simply class?

    As I continue my reading into various books there are some books which will have you add the access modifier public in front of your classname. Other books will just have you leave it out. I tried out a simple program that declared a class in a separate file and then the second file was the main class file with the main method.
    It didn't matter whether or not I removed the keyword public in front of the name of my class in the first file. The program compiled and ran just fine. So I'm doing some looking on the web trying to understand what the word public means when it's placed in front of your classname.
    According to Sun:
    A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes?you will learn about them in a later lesson.)
    I picked this up from some other source:
    Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package.
    So if I understand this correctly if I place the word public in front of my classname my class is visible to all classes and all packages?
    And if I don't place the word public in front of my classname then the class that I defined is only accessible only by other classes in the same package whatever that package happens to be?
    So if I wrote this:
    public class MyVehicle
    }Then if I imported a package called import.java.GiveMeSomePaintingTools;
    Then the classes contained in the GiveMeSomePaintingTools would have access to the MyVehicle class that I made?
    And if I just wrote this:
    class MyVehicle
    }Then the classes in the package GiveMeSomePaintingTools would not have access to the class I made?
    That's what I gather...
    Edited by: 357mag on Jun 3, 2010 5:53 AM

    357mag wrote:
    Then the classes in the package GiveMeSomePaintingTools would not have access to the class I made?The clue as to what access modifier to use for a class will often be in its name. Generally you write a class to do something. If what it does is something you want the whole world to be able to do, then use public; if it is only used by other classes of a package you've written, then use the default. The third one is protected: you use this when the class needs to be visible within a hierarchy (especially one that can be extended by anyone).
    As an example: [java.math.BigInteger|http://java.sun.com/javase/6/docs/api/java/math/BigInteger.html] is a class that allows you to store arbitrarily large integer values. Sun clearly felt that this was useful enough to allow anyone to have access to it, so it is public. However, it is defined as immutable: ie, once you've created a BigInteger object, you cannot change its value. This is not optimal for arithmetic, where you may have several operations to perform to get a result: If each of them is forced to create a new object, you could waste a lot of time (and space).
    So the designers created a class called MutableBigInteger which is used by the BigInteger class (and also by BigDecimal) to hold interim values for calculations. Since this class is only used by those classes, it is defined with the default modifier (which is why you've never seen it).
    HIH
    Winston

  • How to reach a method of an object from within another class

    I am stuck in a situation with my program. The current situation is as follows:
    1- There is a class in which I draw images. This class is an extension of JPanel
    2- And there is a main class (the one that has main method) which is an extension of JFrame
    3- In the main class a create an instance(object) of StatusBar class and add it to the main class
    4- I also add to the main class an instance of image drawing class I mentioned in item 1 above.
    5- In the image drawing class i define mousemove method and as the mouse
    moves over the image, i want to display some info on the status bar
    6- How can do it?
    7- Thanks!

    It would make sense that the panel not be forced to understand its context (in this case a JFrame, but perhaps an applet or something else later on) but offer a means of tracking.
    class DrawingPanel extends JPanel {
      HashSet listeners = new HashSet();
      public void addDrawingListener(DrawingListener l) {
         listeners.add(l);
      protected void fireMouseMove(MouseEvent me) {
         Iterator i = listeners.iterator();
         while (i.hasNext()) {
            ((DrawingListener) i.next()).mouseMoved(me.getX(),me.getY());
    class Main implements DrawingListener {
      JFrame frame;
      JLabel status;
      DrawingPanel panel;
      private void init() {
         panel.addDrawingListener(this);
      public void mouseMoved(int x,int y) {
         status.setText("x : " + x + " y: " + y);
    public interface DrawingListener {
      void mouseMoved(int x,int y);
    }Of course you could always just have the Main class add a MouseMotionListener to the DrawingPanel, but if the DrawingPanel has a scale or gets embedded in a scroll pane and there is some virtual coordinate transformation (not using screen coordinates) then the Main class would have to know about how to do the transformation. This way, the DrawingPanel can encapsulate that knowledge and the Main class simply provides a means to listen to the DrawingPanel. By using a DrawingListener, you could add other methods as well (versus using only a MouseMotionListener).
    Obviously, lots of code is missing above. In general, its not a good idea to extend JFrame unless you really are changing the JFrames behavior by overrding methods, etc. Extending JPanel is okay, as you are presumably modifiying the drawing code, but you'd be better off extending JComponent.

  • How to access AppModule methods into View Controller project

    Hi,
    I've created AppModule in model project and now I want to use that AppModule methods into viewcontroller project without creating the webservice proxy.
    Thanks in advance,
    Rohit

    Hi,
    I am using Jdeveloper 11.1.1.4.0.
    To use the appModules methods, I am creating the service interface and then I am creating the webservice proxy into another view controller project and access the appModule methods.
    Now, I don't want to create the webservice proxy. I want to directly access the appModule methods.
    Thanks,
    Rohit.

  • My phone is not working properly and i have applied for it to be fixed. i was told a box would arrive for me to send it manufacturer but no box as of yet and i dont know how to access the tracking. i have the info just dont know where to put it??

    please contact me if you know how i can see where the box is and the phone (when i send it off) i have the case id and carrier tracking number but dont know where to access it ? assuming its a simple answer?

    Hello jesswrenn
    There are a few options to look that up. Check out the links below to look up the status of your repair.
    Check Your Service and Support Coverage
    https://selfsolve.apple.com/agreementWarrantyDynamic.do
    Look Up a Repair
    https://selfsolve.apple.com/repairstatus/main.do
    Regards,
    -Norm G.

Maybe you are looking for

  • Append date to exporting file name in SQL reporting service

    When exporting a report to another format, say excel,PDF; the file name is always set to the report name. Our client has a requirement where whenever a user exports a report to pdf, the timestamp of when the data of the report was made should be appe

  • Problem in Creating Shipment using BAPI

    Hi All, I am using the bapi BAPI_SHIPMENT_CREATE for creating shipment for deliveries in my program. When I schedule it in the background (i.e.SM37) the job gets cancelled when there is a dynamic credit block (Message type is E). When I execute the p

  • Move Web Gallery

    I maintain two copies of aperture one on my MBP local hard drive and one on a remote HD. I export projects I've made while traveling, off of my local HD to the remote HD to leave room on the MBP. I made a Web Gallery on the local and unlike the proje

  • HT204187 outgoing mail rejects password on one computer but not the other

    The mail program says the outgoing mail password is incorrect on wife's desktop computer, but mail works from her iPad.

  • Unable to update flash player

    Unable to update flash player:  "Please quit the followiing programs to continue:  PluginProcess