Variable class names,QUESTION

how do I get information from a class using a String for the class name? (in an applet)

whether you are in an applet or java application, just use Class.forName to retrieve a java.lang.Class instance for that class- then you can get field or method informaiton. There are additional security restrictions in applets, so you may not have access to the particular class, but, if it is accessible, java.lang.Class.forName("yourClassName") is the best choice.

Similar Messages

  • QUESTION, variable class names!!!

    I've tried to use Class.forName(variableName) to load a class using a String, but during compilation, I get an error. The variable variableName isn't defined in java.lang.Class. Is this an applet problem or is my program messed?

    paste some code around the line
    Class.forName(variableName);
    especially how you define variableName.
    --lichu                                                                                                                                                                                                                                       

  • Variable Class Names?

    My current project uses a Movie Class and a Frame Class (amongst others)
    I need to create multiple instances of the Frame Class.
    Frame frame1 = new Frame(s, n);
    Frame frame2 = new Frame(s, n); etc...
    is it possible to do 'something like'
    Frame frame+i = new Frame(s, n);?
    All help is greatly appreciated, thanks.

    And if you don't know ahead of time how many Frames there will be:
    List<Frame> frameList = new ArrayList<Frame>();
    while (there are more Frames to be added) {
      frameList.add(the next frame);
    }[http://java.sun.com/docs/books/tutorial/collections/]

  • AS3 - dynamic class names with *new* operator

    I'm using AcrtionScript 3 and Adobe Flash 9 Public Alpha.
    I have 50 movie clips in the Library that use Linkage to set
    the Class name to: Img1, Img2, Img3, ..., Img50.
    I have a parent class named RandImg. I want the constructor
    for RandImg to randomly select one of the 50 movie clips from the
    Library and display it. I could get this working by generating a
    random number, and then writing a really huge switch statement to
    associate each possible random number with its respective Library
    Movie Clip Class name, but I would much rather do this with a
    dynamic/variable class name based on the random number, such as:
    var nImgChoice:Number = Math.floor( Math.random( ) * 50 ) +
    1;
    var mcImg:MovieClip = new [ "Img"+String(nImgChoice) ] ( );
    addChild( mcImg );
    Note that this used to be possible in AS 2 by doing the
    following:
    this.attachMovie( "Img"+String(nImgChoice) , "mcImg",
    this.getNextHighestDepth());
    Suggestions?
    Thanks,
    ~JC

    import flash.display.DisplayObject;
    import flash.display.Sprite;
    import flash.utils.getDefinitionByName;
    var nImgChoice:Number = Math.floor( Math.random( ) * 50 ) +
    1;
    var ClassReference:Class =
    getDefinitionByName("Img"+String(nImgChoice) ) as
    Class;
    var instance:Object = new ClassReference();
    addChild(DisplayObject(instance));

  • Declare a variable typed "name of a class"-Need help

    I have "segment" class in package named Ex13
    import Exercise12.Point123;
    public class segment {
         private Point123 start;
         private Point123 end;
         public segment(Point123 start, Point123 end) {
              this.start = start;
              this.end = end;
         public double length() {
              return start.distance(end.getX(), end.getY());
         public String midlePoint() {
              return (end.getX() + start.getX()) / 2 + " "
                        + (end.getY() + start.getY()) / 2;
              // return insidePoint(1,1);
         public Point123 insidePoint(double m, double n) {
              double ratio = m / (m + n);
              return new Point123(start.getX()+(end.getX() - start.getX()) * ratio,
                        start.getY()+(end.getY() - start.getY()) * ratio);
    //return (start.getX()+(end.getX() - start.getX())*ratio);
    }And class "Point123" in package Ex12:
    public class Point123 {
         private double x;
         private double y;
         public Point123(double xAsis, double yAsis) {
              x = xAsis;
              y = yAsis;
         public double getX() {
              return x;
         public double getY() {
              return y;
    //     public String toString() {
    //          return String.format("%.1f,%.1f", x, y);
         public boolean isOrigin() {
              return x == 0 && y == 0;
         public boolean isOnX_Axis() {
              return y == 0;
         public boolean isOnY_Axis() {
              return x == 0;
         public double distance(double xAsis, double yAsis) {
              return Math.sqrt(Math.pow(xAsis - x, 2) + Math.pow(yAsis - y, 2));
    }I remove toString method in Point123 class, but whenever I call insidePoint method in segment class it print out "Exercise12.Point123@addbf1". In other hand, I don't remove toString method, I call insidePoint method,then it prints out the correct result which I want.
    I think the reason why this thing happened is that I am using Point123 return type in insidePoint method. To midlePoint method in segment class, it does not affect whether I remove toString or not. That is because I use its own String return type.
    Can someone tells me whether my thought is correct or not? And explain more about variable typed "name of a class"

    Oh! My header's segment class does not have extend...., therefore it inherit from the Object. But what is Object in my class?
    is it "*s*" in my code?
    public class DisplayResult {
         public static void main(String[] args) {
                   segment s  = new segment(new Point123(3,4), new Point123(6,7));
                   System.out.println(s.length());
                   System.out.println(s.midlePoint());
                   System.out.println(s.insidePoint(1.5,4));
    }

  • Undefined variable or class name

    I am trying to call a java class to another class but gets the error: "Undefined variable or class name"
    Both my java files are in the same directory and I am able to compile only one of the program. Wondering what am I missing?
    The source code is:
    ServletUtilities.java: (I am able to compile)
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class ServletUtilities {
    public static final String DOCTYPE =
         "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
         "Transitional//EN\">";
    public static String headWithTitle(String title) {
         return(DOCTYPE + "\n" +
              "<HTML>\n" +
              "<head><title>" + title + "</title></head>\n");
    HelloWWW3.java (getting error when compile)
    public class HelloWWW3 extends HttpServlet {
    public void doGet(HttpServletRequest request,
                   HttpServletResponse response)
         throws ServletException, IOException
         response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println(ServletUtilities.headWithTitle("Hello WWW") +
              "<body>\n" +
              "<h1>Hello WWW</h1>\n" +
              "</body></html>");

    I tried and I got these errors:
    C:\java servlets\HelloWWW3\src>javac -classpath . HelloWWW3.java
    HelloWWW3.java:4: Package javax.servlet not found in import.
    import javax.servlet.*;
    ^
    HelloWWW3.java:5: Package javax.servlet.http not found in import.
    import javax.servlet.http.*;
    ^
    HelloWWW3.java:7: Superclass coreservlets.HttpServlet of class coreservlets.Hell
    oWWW3 not found.
    public class HelloWWW3 extends HttpServlet
    ^
    3 errors
    Then I moved HelloWWW3.java and ServletUtilities.class file to C:\jakarta-tomcat-3.2.3\lib
    This dir has files
    JAXP JAR
    SERVLET JAR
    ANT JAR
    PARSER JAR
    WEBSER~1 JAR
    JASPER JAR
    and compiled and got this error
    C:\jakarta-tomcat-3.2.3\lib>javac -classpath . HelloWWW3.java
    HelloWWW3.java:4: Package javax.servlet not found in import.
    import javax.servlet.*;
    ^
    HelloWWW3.java:5: Package javax.servlet.http not found in import.
    import javax.servlet.http.*;
    ^
    HelloWWW3.java:7: Superclass coreservlets.HttpServlet of class coreservlets.Hell
    oWWW3 not found.
    public class HelloWWW3 extends HttpServlet
    ^
    3 errors
    Here is what I hava defined for my CLASSPATH
    C:\jakarta-tomcat-3.2.3\lib>echo %CLASSPATH%
    C:\jakarta-tomcat-3.2.3\lib\servlet.jar;C:\jakarta-tomcat-3.2.3\lib\jasper.jar
    ------------------------------------------

  • Undefined variable, class, or package name

    The following code in the jsp is supposed to display the correct 'Securities' link based on the app_main_frames URL. I am getting an error. Can anyone help?
    <% if (parent.app_main_frame.location == ("http://ccmsun57.ccminvest.com:8080/cgi-java/Allocation/jsp/scenario.jsp?source=init")) { %>
    Securities
    <% } else { %>
    <a href="/cgi-java/Holdings/jsp/SecurityInventoryQuery.jsp?which_search=none&which_category=none
    target="app_main_frame">Securities</a>
    <% } %>
    I am getting the following error:
    Generated servlet error:
    /opt/JBoss-2.4.4_Tomcat-4.0.1/catalina/work/localhost/cgi-java/common/jsp/NavigationMenu$jsp.java:173:
    Undefined variable, class, or package name: parent
    if (parent.app_main_frame.location ==
    ^
    ("http://ccmsun57.ccminvest.com:8080/cgi-java/Allocation/jsp/scenario.jsp?source=init")) {

    If app_main_frame is a frame in a frameset then you cannot
    simply refer to it in a Java scriptlet.
    You can refer to it in a JavaScript script, like this:
    <script>
    if (parent.app_main_frame.location == "http://ccmsun57.ccminvest.com:8080/cgi-java/Allocation/jsp/scenario.jsp?source=init")
       document.write("<a href=\"javascript:submit_Form('none')\"target=\"app_main_frame\">Securities</a>");
    else
       document.write("<a href=\"/cgi-java/Holdings/jsp/SecurityInventoryQuery.jsp?which_search=none&which_category=none\"target=\"app_main_frame">Securities</a>");
    </script>

  • How to convert a String variable as class name and method name?

    i have two classes
    class Student
    public String insertStudent(String sname)
    { return("Student has been inserted ");     }
    class Teacher
    public String execute(String methodName, String className)
    {  //return statement of the method 'insertStudent' in the class 'Student'; }
    }Now, i have a class with the main method. Here, i would like to call the method *'insertStudent'* of class *'Student'*
    using the method *'execute'* of class *'Teacher',* passing the method-name and the class-name (viz. insertStudent, Student) as the
    String parameter.
    Can anyone please help me out. Thanks
    regards,
    chinglai

    You should have just added that as a comment on your [initial posting|http://forums.sun.com/thread.jspa?threadID=5334953] instead of starting a new thread.
    Now, i have a class with the main method. Here, i would like to call the method 'insertStudent' of class 'Student'using the method 'execute' of class 'Teacher', passing the method-name and the class-name (viz. insertStudent, Student) as the
    String parameter.
    Why oh why? What do you want to achieve?
    Let me tell you: there is a way to do what you try to do, but it's not recommended and should be used only very sparingly. Especially not in anything like your code, that resembles normal business logic (as opposed to an application framework such as Spring, for example).
    Can you explain what exactly you want to do with that? Why should a Teacher be able to call any random method ony any other class. And what good would that do?

  • Quick question about class name

    I was reading through some java code and i noticed this line on the class name
    public class SimpleList<E> implements List<E>i was just wondering what does <E> refer too? I'd appreciate any links.
    Thanks

    The <E> portion of class definition is in reference to Generics. Take a look at Generics in the Tutorial.

  • How to get CLASS name for the generic item?

    Hi,
    I wrote following method to create a service instance.
    public static <IType> IType GetServiceInstance()
           IType type=null;
            try
            InitialContext ic=new InitialContext();
    //ERROR:      type=   ic.lookup(IType.class.getName());
            catch(Exception ex)
            //do handle
            return type;
        }please see the //Error: here its giving error, also i m not getting "class" variable in IDE!!!
    i want use like this;
    IUserService userService=ServiceFactory.GetServiceInstance<IUserService>();so how can i do this?
    Edited by: Manikandan.Java on Oct 31, 2007 3:02 AM

    I don't know if I understand your question, but you cannot find the class name because it is in run time just an object. You can, however, check if it is an instanceof.
    if (genericType instanceof MyType) {
         doMyThing();
    }

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

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

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

  • How to programmatically get the source for a class provided the class name?

    Hello,
    As a quick background, I am providing some tools to potential users of an in-house framework. One is the ability to generate quick prototypes from our existing demo applications. Assume a user downloads our jars and uses them in their project (we are using Eclipse, but that detail should not greatly affect my question). Included in the jars is a demos package that contains ready-to-run classes that serve to exhibit certain functionality. Since many users may just need quick extensions of these demos, I am trying to provide a way for them to be able to create a new project that starts with a copy of the demo class.
    So, the user is provided a list of the existing demos (each one uses a single class). When the user makes their selection, with the knowledge of our framework, I can translate that into what demo class they need (returned as a string of format package.subpack1.subpackn.DemoClassName). What I now want to do is to use that complete class name to get the source (look up the file) for the corresponding class, and copy it into to a new file in their project (the copying into the project can be done easily in Eclipse, so what I need help with is the bolded part). Is there a simple way to get the source given a class path for a class as described above? You may assume the source files are included in the jars for the framework.
    Thanks in advance.

    If there's a file named "package.subpack1.subpackn.DemoClassName.java" in a "demos" directory in the jar, then yes. You'd just use
    InputStream code = getResourceAsStream("/demos.package.subpack1.subpackn.DemoClassName.java");Or if those dots in the name actually separate directory names, i.e. you have a "package" directory under "demos" and a "subpack1" director under that and so on, then:
    InputStream code = getResourceAsStream("/demos/package/subpack1/subpackn/DemoClassName.java");

  • Can you determine a dragged objects Class Name when it is dropped?

    Is there a way to determine the class name for a dragged object.
    I have set up two objects. One is a JList that acts as a data source for the second object which is a JTable. Both objects serve as both drag source and drop targets. I need to be able to react to the following events:
    1. Drag value from JList to JTable.
    2. Drag value from JTable to JTable (itself) to reposition order.
    3. Drag value from JTable to JList (deletes item from JTable).
    So far, I have had no problem in getting #1 to work.
    The problem is determining how to consistently interpret which event is happening for 2 and 3. Both the drop (DropTargetDropEvent event) and the dragDropEnd (DragSourceDropEvent event) are fired for either 2 or 3 above. If I could identify the source class for the dragsource and the target class for the droptarget, the coding would be easy. I haven't been able to find anything on this while reviewing the API documentation.
    Any help would be appreciated.
    Thanks

    No, there are not multiple policies - the host names for all aliases on that single webserver are together in a single host identifier. And I realize I can only have a single challenge redirect, I just want to use a variable to redirect to the host name that was accessed as opposed to a static name.

  • Error in File name or class name not found during Automation operation: 'CreateObj​ect'

    Hello Team,
    When I am trying to execute the below code i am getting the following error. Any help would be greatly appreciated.
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    If Not oFSO.FolderExists(SavePath) Then
    Set f = oFSO.CreateFolder(SavePath)
    Else
    End If
    53 4/11/2014 12:27:22 PM Error:
    Error in <NoName(4).VBS> (Line: 9, Column: 1):
    File name or class name not found during Automation operation: 'CreateObject'
    I have googled through the error and tried to re-register the scrrun.dll using regsvr32 eventhogh it is successfully registered, i am getting the following error. My PC is windows 7 32bit OS.
    any help is greatly appreciated.

    The following script class will write a log file entry. See if it will run for you.
    The script is using a class object that you might not have seen before. A little intro:  The top section is just for testing the class. Normally I just comment this out after the class is working well.  It should run right way. I would save the vbs file in the editor, That way when you are using autoactpath or currentscriptpath variables they will be able resolve the paths.
    Paul
    Attachments:
    LoggingCode_V2.VBS ‏5 KB

  • How to get class name of a object in run time, from its accessible context.

    Hi,
    I need to get the class name of a java object in run-time, given the AccessibleContext of that object.
    I gone through the AccessibleContext api documentation. but there is not way to get the class name for a java object using its AccessibleContext object.
    Do any one have any idea how to get the class name of an java object, given its accessible object Accessible.
    Thanks
    Timberlake

    816311 wrote:
    Please try to provide a solution for my requirement and avoid evaluating a requirement.
    I am a curious guyit's great to be curious. however, in this situation, the requirement makes no sense in the given context. so, in an effort to be helpful, the people on this forum are asking you the reason behind the requirement. the reason we do this is because we have experience answering questions on this forum and, more often than not, requirements which don't make sense are the result of misunderstandings or confusion on the part of the person making the requirement. if we can figure out why you want to do what you want to do, we may be able to point you in a direction which makes more sense.

Maybe you are looking for