Generic instance maker and class definition in separate files - problem

file: genericinstantiator.java
package testGenericInstantiator;
public final class GenericInstantiator {
     public <T> T makeInstance(Class<T> c) {
          T instance = null;
          try {
               instance = c.newInstance();
          } catch (IllegalAccessException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (InstantiationException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          return instance;
file: genericinstantiatorusage.java
package testGenericInstantiator.usage;
import testGenericInstantiator.GenericInstantiator;
final class SillyClass {
     public void sayBoo() {
          System.out.println("boo");
public final class GenericInstantiatorUsage {
     public static void main(String[] args) {
          GenericInstantiator gi = new GenericInstantiator();
          SillyClass sc = gi.makeInstance(SillyClass.class);
          sc.sayBoo();
          System.exit(0);
thrown exception:
java.lang.IllegalAccessException
on the line 'instance = c.newInstance();' in instantiator
reason in jdk:
if the class or its nullary constructor is not accessible.
question:
how to avoid this? (in my situation, the place of making instance and its class MUST be separated in another files)
Edited by: gizmo640 on Mar 27, 2008 11:39 AM

package testGenericInstantiator;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public final class GenericInstantiator {
     public <T> T makeInstance(Class<T> c) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
          T instance = null;     
          Class[] emptyParams = {};
          Constructor<T> con = c.getDeclaredConstructor(emptyParams);
          con.setAccessible(true);
          instance = con.newInstance();
          return instance;
}setting constructor to accessible works well too

Similar Messages

  • How do I create an genericized instance of this class?

    Hi, I'm having trouble creating a proper generic instance of this class that I wrote. The class type is cyclic dependant on itself.
    public class MyClass<T extends MyClass<T>>
    I can create an instance like this:
    MyClass<?> class = new MyClass();But I would be mixing raw types and generic types.
    Is there anyway to create a proper generic instance of MyClass?
    Thanks a lot
    -Cuppo

    Ah thanks georgemc,
    your solution will certainly work.
    If i may ask your opinion of something...
    MyClass is designed such that the type parameter should always be the same as the class itself. It's kinda a hack to get the subclass type from the superclass.
    so a hierarchy looks something like this:
    class MyClass<T extends MyClass<T> >
    class SubClass<T extends SubClass<T>> extends MyClass<T>
    class FinalSubClass extends SubClass<FinalSubClass>So ideally i would want something like:
    MyClass m = new MyClass<MyClass>();
    (which is not possible)
    is there a way to get around this?
    -Cuppo

  • What is the difference between instance variable and class variable?

    i've looked it up on a few pages and i'm still struggling a bit maybe one of you guys could "dumb" it down for me or give and example of how their uses differ.
    thanks a lot

    Instance is variable, class is an object.What? "Instance" doesn't necessarily refer to variables, and although it's true that instances of Class are objects, it's not clear if that's what you meant, or how it's relevant.
    if you declare one instance in a class that instance
    should be sharing within that class only.Sharing with what? Non-static fields are not shared at all. Sharing which instance? What are you talking about?
    if you declare one class object it will share
    anywhere in the current program.Err...you can create global variables in Java, more or less, by making them static fields. If that's what you meant. It's not a very good practice though.
    Static fields, methods, and classes are not necessarily object types. One can have a static primitive field.

  • Class methods in separate file

    I have created a class and I want to put each method in its own separate file in order to not to have one huge file
    Can I do this, and if so how?

    Adding to that...
    In the vast majority of cases if your source file is huge then your design is bad. Very bad.
    (On the upside, if someone is trying to produce job security, then creating large un-maintainable god classes, guarantees that no one will ever be able to get rid of that person. At least not if the application needs to change in the next several years.)

  • Exporting Issue: One large frame sized project, needs to be split and exported in 3 separate files

    Hello Awesome people, help me out here Please!
    I have a 4480(W) 1260 (H) frame sized project which needs to be exported in 3 separate files, due to the large screen size at the venue.
    how to split one project into 3 so that I can get 2 x 1920 (W) and 1 x 640 (W), and height for all three would be 1260 (H)??

    Dear Evans,
    You might need to check the print preferences settings on the system. This is available from Administration -> System Initialization -> Print Preferences.
    Check this out for the documents that get printed as images and get stored in the Bitmaps folder. Check under the 'general' tab whether the check box for printing documents as images is ticked. If yes, untick this. Then check the settings under the 'Per Document' tab - you will need to change the settings per each document.
    I hope this helps.
    Regards,
    Davis M Onsakia

  • IDVD doesn't process AVCHD video and high definition RAW photo files

    Hi everybody. I have a brand new Canon VIXIA HF S10 and 5D Mark II. I tried to make a movie out of video shot with the camcorder using iMovie and then I burned a DVD with iDVD. I also made a slide show out of RAW photos made by the 5D. And I encountered such a situation when the movies I made seem to be missing some frames. For instance people move discretely instead of smoothly as in the original video. As for the photos they come out not to be of high definition and don't fit to the whole TV screen. I mean if I burn the photos to a DVD in Jpeg they look perfect. I set all the setting to HD but still get poor quality.
    Have anybody dealt with the same situation or I should try more professional soft like Cut pro or DVD pro?

    IDVD can't process AVCHD. I use Toast to do that. Import your pictures or slides into IMovie and export them via Quicktime if you want 1920x1080 or via browser if you want 720P. Than you can us the browser in Toast to create a DVD in AVCHD. It will play in a blu ray player but NOT in Mac OSX. You will need to use Native Windows via Boot Camp and a Blu Ray player in your mac if you have one. Otherwise a Blu Ray player in you TV system should work.

  • Streaming data and writing data to measurement file problem

     Hi everyone,
    I found something wrong about my code but i don't know exactly what it is first i have a program for acquiring 15 analog signals(NI PXI6259) after acquiring the data i use network stream to stream data from my NI PXI8186 to the host pc these steps are in target VI, after streaming data to host PC
    , i tried to write down the data to the spreadsheet using Express write to measurement VI.
    Problems : 1. After i run the host Vi and target Vi the number available to read is always 0 after sometimes the data displaying on the chart incdicator on host Vi is stopped and start counting the numberavailable to read also the time indicated on X axis of the chart doesn't grow.
                         2. Write to measurement file generate the file that record the data counting the data from 0 to 99 and start over and over again
     Please help i really have no idea what is the cause for each problems.
    Attachments:
    target - single rate.vi ‏83 KB
    Host UI.vi ‏36 KB

    Dear Crossrulz
            Thank you for your prompt reply i have removed the input to "Samples Per Channel" on the DAQmx Timing VI already but still didn't arrange the 
    channels input i will do it but i want to keep it this way first. Now the data acquiring looks okay but i have found new problem.
            After running the program for acquiring the data for about 5 to 6 minutes the program will stop acquiring the data or
    sometimes the target (NI pxi8186) will reboot itself and displaying message "Reboot due to system error" "System state: Safe Mode (System error)
    and on the Host PC there will be a window pop-up displaying
    "Waiting for the target (NI-PXI8186-2F0a597C) to respond"  "Stop Waiting and Disconnect"
     i didn't run the host Vi just run the target Vi only. If this problem caused from the program or the hardware ? Please help.
    Attachments:
    Host UI.vi ‏141 KB
    target - single rate.vi ‏83 KB

  • Android reader and Paperport 12 created PDF files problem

    i am having a problem with Android reader and documents created with nuance Paperport 12. The documents are a uniform 380k and contain a scanned monochrome image. The problem is as follows - When I open the document the page displays correctly but is way too small to be read on the device. The device is a Sony Ericsson Xperia X10 mini running Android 2.1 update 1. I have duplicated the problem exactly on a Sony Ericsson Xperia X10 mini pro.
    What happens is when you zoom in on the document the page goes blank. There are no restrictions or security options on the document and the metadata shows nuance Paperport 12 as the creator. I can zoom in on the document on any other device other than the android handsets.

    i am having a problem with Android reader and documents created with nuance Paperport 12. The documents are a uniform 380k and contain a scanned monochrome image. The problem is as follows - When I open the document the page displays correctly but is way too small to be read on the device. The device is a Sony Ericsson Xperia X10 mini running Android 2.1 update 1. I have duplicated the problem exactly on a Sony Ericsson Xperia X10 mini pro.
    What happens is when you zoom in on the document the page goes blank. There are no restrictions or security options on the document and the metadata shows nuance Paperport 12 as the creator. I can zoom in on the document on any other device other than the android handsets.

  • JSP and classes

    I created a JSP file in ..webapps/myapp folder .I want to create my own DateFormatter class in a separate file and use this class in the JSP file.I tried putting it in .../WEB-INF/classes folder but it gives error
    An error occurred at line: 43 in the jsp file: /myformconfirm2.jsp
    DateFormatter cannot be resolved to a type.I even tried creating a package under /WEB-INF/classes but theres no use...ne suggestions???am i supposed 2 add entry in web.xml?

    Hi Amit,
    I have this code for tree generation
    can u please guide me for display this in a JSP page
    or if u can plz send me the code too for that
    please..
    package net.sf.jsptree.example;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.AbstractCollection;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.List;
    import java.util.StringTokenizer;
    import java.util.Vector;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipInputStream;
    import javax.swing.tree.DefaultMutableTreeNode;
    import net.sf.jsptree.component.JSPTreeNode;
    import net.sf.jsptree.component.JSPTreeNodeImpl;
    import net.sf.jsptree.tree.*;
    * @author Vladislav Kamensky
    public class TestFactory implements TreeFactory {
        private static TreeFactory m_instance = new TestFactory();
        TestFactory() {
        public static TreeFactory getInstance() {
            return m_instance;
         * Returns new <code>Tree</code> instance by its name.
         * @param p_name The name of the tree to be built.
        public TreeStructureModel getTree(String p_name) {
            return buildTree();
        static TreeStructureModel a_tree = new TreeModel();
        static TreeStructureModel tree= new TreeModel();
        static JSPTreeNodeImpl parentJSPTreeNodeImpl = null;
        static JSPTreeNodeImpl parentDirJSPTreeNodeImpl = null;
        static List list = new ArrayList();
        static JSPTreeNodeImpl curDir=null;
        static JSPTreeNodeImpl tempJSPTreeNodeImpl = null;
        String sss="D:\\com";
    JSPTreeNodeImpl addNodes(TreeStructureModel tree, JSPTreeNodeImpl curTop, File dir) {
            String curPath = dir.getPath();
            //String sss=dir.
            curDir =new JSPTreeNodeImpl(dir.getPath());
            curDir.setLabel(dir.getName());
            if (curTop != null) { // should only be null at root
                 //curTop.addProperty(curDir);// add(curDir);
                 tree.addChildToParent(curTop,curDir);
            Vector vc = new Vector();
            String[] tmp = dir.list();
            for (int i = 0; i < tmp.length; i++)
              vc.addElement(tmp);
    Collections.sort(vc, String.CASE_INSENSITIVE_ORDER);
    File f;
    Vector files = new Vector();
    // Make two passes, one for Dirs and one for Files. This is #1.
    for (int i = 0; i < vc.size(); i++) {
    String thisObject = (String) vc.elementAt(i);
    String newPath;
    if (curPath.equals("."))
    newPath = thisObject;
    else
    newPath = curPath + File.separator + thisObject;
    if ((f = new File(newPath)).isDirectory())
    addNodes(tree,curDir, f);
    else
    files.addElement(thisObject);
    // Pass two: for files.
    //JSPTreeNodeImpl tempJSPTreeNodeImpl = null;
    for (int fnum = 0; fnum < files.size(); fnum++)
         String s=(String)files.elementAt(fnum);
         tempJSPTreeNodeImpl=new JSPTreeNodeImpl((String) files.elementAt(fnum));
         tempJSPTreeNodeImpl.setLabel((String) files.elementAt(fnum));
         //tempJSPTreeNodeImpl.addProperty("fileName","Amit");
         //tempJSPTreeNodeImpl.setContextRelative(true);
         //tempJSPTreeNodeImpl.setId(sss+"\\"+s);
         tempJSPTreeNodeImpl.setId(sss);
         //tempJSPTreeNodeImpl.setHref("");
         System.out.println("******************************"+tempJSPTreeNodeImpl);
         tree.addChildToParent(curDir,tempJSPTreeNodeImpl);
         curDir.addProperty("tempJSPTreeNodeImpl","files");
    // curDir.addProperty(new JSPTreeNodeImpl((String) files.elementAt(fnum)));
    return curDir;
    private TreeStructureModel buildTree() {
    TreeStructureModel tree = new TreeModel();
    //TODO
         try {
              File dir=new File(sss);
              //TestFactory.recursivelyDeleteDirectory(new File("D:\\com"));
              JSPTreeNodeImpl jspTreeNodeImpl = new JSPTreeNodeImpl("Applicare","Applicare");
              tree.setRoot(jspTreeNodeImpl);
              //tree.addChildToRoot(new TreeModel(addNodes(null, dir)));
              tree.addChildToRoot(addNodes(tree,jspTreeNodeImpl, dir));
              System.out.println(dir);
              //a_tree.setRoot(new JSPTreeNodeImpl("Applicare","Applicare"));
              //a_tree=tree;
         //a_tree.addChildToRoot(tree);
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    return tree;
    public TreeStateModel getTreeStates(String p_name) throws TreeFactoryException {
    DefaultTreeStateModel defaultTreeStateModel = new DefaultTreeStateModel();
    defaultTreeStateModel.addOpened(new JSPTreeNodeImpl("1").hashCode());
    defaultTreeStateModel.addOpened(new JSPTreeNodeImpl("4").hashCode());
    defaultTreeStateModel.addOpened(new JSPTreeNodeImpl("5").hashCode());
    return defaultTreeStateModel;

  • Unable to make a new instance of a class?

    Why can't I make a new instance of this object?
    This doesn't work:
            static void generateConfirmationDialog(String s1, String s2,
                String s3)
                int optionConfirmation = JOptionPane.showConfirmDialog(null,
                    "Confirm inputs: \n" +
                    "\n1: " + s1 +
                    "\n2: " + s2 +
                    "\n3: " + s3,
                    "Input Confirmation",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
                if (optionConfirmation == JOptionPane.YES_OPTION)
                    //A new instance of an object.
                    //Class UserInterface
                    //Inner Class FileChooser
                    UserInterface.FileChooser fc = new
                        UserInterface.FileChooser.FileChooser();
                else if (optionConfirmation == JOptionPane.NO_OPTION)
                    //Returns the user to the main menu, with inputs intact.
            }Here's that class:
        public class FileChooser extends JFrame
            FileChooser()
                JFileChooser filechooser = new JFileChooser();
                int returnValue = filechooser.showDialog(this, "Upload");
                //Not done yet, but it should be able to display it
        }But this works:
        public static void main(String args[])
            UserInterface menu = new UserInterface();
        }

    1. Does class FileChooser need direct access to any nonstatic member variables or methods in the enclosing class (by your claim UserInterface)?
    If not, then just make the nested class static by:public static class FileChooser extends JFrame
        // body
    }note the static qualifier in the class definition. People frequently make inner classes where static nested classes would do equally as well or even better. Only if the nested class is "attached" to the instance is it necessary to make it non-static.
    2. If so, does the generateConfirmationDialog() have to be static?
    If not, simply remove the static qualifier from the method.
    3. If so, you will have to pass the instance created in your main() method to the method and use it to instantiate the inner class. The syntax isUserInterface menu = new UserInterface();
    FileChooser fc = menu.new FileChooser();4. Is there some reason you can't just use a filechooser from Swing?

  • Nested classes and separate files in Javadoc...

    Hello. I am writing an application, and it has several .java files, and some of the classes contained therein contain nested classes, for example
    ClassOne.java
    class ClassOne
    // stuff
       class innerClassOne
          //more stuff
    }ClassTwo.java
    class ClassTwo
    // stuff
       class innerClassTwo
          //more stuff
    }What I want to do is generate documentation like the online java documentation for my app, that is, documentation that will contain ALL the classes and nested classes involved, and link everything that comes in java already to the sun online java docs.
    I've figured out the -link command for javadoc, and I can make that work, but I've run into some other snags.
    1.) Javadoc isn't finding or documenting my nested classes, despite them being marked up. Google does not wish to help.
    2.) Some classes reference other classes of mine that aren't conatined in the same .java file, but do exist in their own .java files in the dame local directory. Javadoc does not like this, and gives errors.
    3.) Running javadoc on one file at a time overwrites the old file's documentation, thus I cannot seem to get an index.html javadoc file that links to all my classes, nor can I get the classes to link to each other.
    What do I need to do to fix these?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • How do I make an instance of another class??

    How do I make an instance of a class, (eg. the name of the class is oldJava.class and have a constructor that takes 3 parameters)in a new class. and send paramaters to the oldJava.class constructor. I also want to recive the result from oldJava.class in my new class.
    ??I would be really glad if I could get some code example.....
    //HA

    oldJava o = new oldJava(..., ..., ...); // your arguments here
    o.method1(); // you can call methods on this object now
    // If the method returns anything back, you can keep a reference to it
    int result = o.sum(2, 5);

  • Do we have to separate java source files and class files after compiled..

    Hi,
    I really confussed with this:
    I have compiled java source files into a package and tried to use but the classes can not be found. Should I separate class and source files after compiled with packages names. I hope you understand what i mean.
    Thank you
    So Jag

    You can choose to separate the source files or not. It sounds like your problem has to do with Classpath and packages.
    If the file c:\base\compute\engine\mysourcefile.java starts with the statement "package engine;" then the fully qualified name of the class is is engine.mysourcefile. If the file c:\base\compute\client\mysourcefile.java starts with the statement "package client;" then its fully qualified name is client.mysourcefile.
    In your source files, whenever you refer to a class from another class, the compiler needs the fully qualified class name. You can either import the class or use the fully qualified name. In order for the compiler to find the class, the c:\base\compute directory must be in the Classpath (assuming the package definitions from above).
    Finally, to launch an application given the above, the command would be "java client.mysourcefile" assuming the main method is in client.mysourcefile.

  • Servlet and Class instances

    Under normal conditions a web-container creates only one instance of servlet.Now the case is I am creating instance of a class in the servlet.So for every request to the servlet does an instance of the class is created?

    If you make the instance in a service method (service(), doGet(), doPost() etc...) then yes, each request will create a new instance.
    If you create the instance anyplace else, no they will share it.
    If you hold the reference to the class in the servlet class level as opposed to storing it in the method which creates and uses it, then you can run into problems as well, since there will be only one reference for all requests.
    So generally speaking in Servlets (and in any application you need to worry about thread safety:
    This is bad. One object will be used by all requests:
    public class BadServlet ... {
        Object myObject = new Object();
        public void doGet(...) ... {
            do something with myObject;
    }This is bad. A new instance is made for each request, but only one reference. So one request will end up using another's instance:
    public class BadServlet ... {
        Object myObject;
        public void doGet(...)... {
            myObject = new Object();
            do something with myObject;
    }This is how you would do it in a thread safe manner:
    public class GoodServlet ...{
        public void doGet(...)... {
            Object myObject = new Object();
            //Another method in same class needs a reference?  Pass it as a parameter
            someOtherMethod(myObject);
            //Some other servlet needs access?  Store it in Request scope
            request.setAttribute("myObject", myObject);
            //Some other request needs to access it?  Put it in the session scope
            HttpSession session = request.getSession();
            session.setAttribute("myObject", myObject);
        private void doSomething(Object myObject) ... {
            do something with myObject
    }

  • How to create the instance of a class and to use this object remotely

    I have to change a standalone program to do it working on a local net.
    the program is prepared for this adjustment, because the only problem for this change came from the use of the database; and, in the application, all the accesses to the database come from only a class that supplies a connection to the database.
    In this way I think that I could have (in a local net) a "server application" that has the database embedded inside it.
    Furthermore, some client applications (running in different computers of the net) could get access to the database through the connection that comes from an instance of the class that, in the "server application", is made to provide the connection to the database.
    I think this could be a good idea...
    But I don't have practice with distributed applications and I would ask some suggestion about the way to realize my modification.
    (in particular how to get and use, in the "client applications", the instance of the class that give the connection to the database from the "server application").
    I would have some help..
    thank in advance
    regards
    tonyMrsangelo.

    tonyMrsangelo wrote:
    I have to change a standalone program to do it working on a local net.
    the program is prepared for this adjustment, because the only problem for this change came from the use of the database; and, in the application, all the accesses to the database come from only a class that supplies a connection to the database.
    In this way I think that I could have (in a local net) a "server application" that has the database embedded inside it.
    Furthermore, some client applications (running in different computers of the net) could get access to the database through the connection that comes from an instance of the class that, in the "server application", is made to provide the connection to the database.
    I think this could be a good idea... Which is why JEE and implementations of that exist.
    But I don't have practice with distributed applications and I would ask some suggestion about the way to realize my modification.
    (in particular how to get and use, in the "client applications", the instance of the class that give the connection to the database from the "server application").
    You can't pass a connection from a server to a client. Nothing will do that.
    As suggested you can create a simple RMI server/client set up. Or use a more feature rich (and much more complex) JEE container.
    RMI is simple enough for its own tutorial
    [http://java.sun.com/docs/books/tutorial/rmi/index.html]
    JEE (previously called J2EE) is much more complex and requires books. You can get a brief overlook from the following
    [http://java.sun.com/javaee/]

Maybe you are looking for

  • No data in the activity monitor

    All of a sudden I don't have any data in the activity monitor. Here's what happened. I was using safari viewing online pictures. I kept getting the rolling ball between pictures and noticed that safari was using 100%+ in processor usage and safari se

  • Energy Manager interface with Outlook on Yoga 2 Pro

    I have a new Yoga 2 Pro and also have Outlook installed with two mail profiles defined. Whenever a reboot the machine I get a mail popup asking which profile I want to use. I have turned off the option in settings to use outlook so I'm not sure why t

  • How to transfer music to a new computer (PC)?

    Simple question, I'm hoping for a simple answer. I've just purchased a new laptop PC and want to transfer my music to it. Is there an easy way to do this? All I can seem to find are some really convoluted steps to making this happen. And if I take th

  • How can I correct distortion in stills?

    Iwould like to correct lens distortion in aperture 3. How can I do this? Stefan

  • The study guide for P_FINACC_65

    Want to know any study materials for self-study purpose to master Financial Account with SAP ERP and prepare the certification test for P_FINACC_65 (SAP Certified Application Professional - Financial Accounting with SAP ERP 6.0 EHP5)? Thanks in advan