Results 1 to 2 of 2
  1. #1
    jon80's Avatar
    jon80 is offline Senior Member
    Join Date
    Feb 2008
    Malta (EU)
    Rep Power

    Default [SOLVED] [newbie] getting the constructors of a class (java.lang.reflect)

    I'm trying to read the exceptions that a class reads (dynamically):

    Java Code:
    public static void readClass (Class<?> class1) {
    		Class _cl = class1.getClass();
    		Class classParams = class1.
    [B]Class<?>[] _classExceptions = class1.getConstructor(er?).getExceptionTypes();[/B] //stuck!
    I've been through the API but it doesn't say anything which I can understand :)


  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    New Zealand
    Rep Power


    To find the exceptions that may be thrown by a constructor for some type, (1) Get a class representing that type (2) And a Constructor representing the constructor you are interested in (3) Call getExceptionTypes() and look at the returned array. It will contain one entry for each of the different exceptions that can be thrown.

    The following code illustrates this for the Class instance representing the Integer type. When you use the constructor which takes a string argument various things can go wrong - there are three examples of this. The last line of the output comes from using the reflection mechanism to ask the Constructor instance directly what exceptions it throws.

    Java Code:
    import java.lang.reflect.Constructor;
    public class ConstructorExceptions {
        public static void main(String[] args) {
            String[] data = {null, "foo", ""};
            for(String str :data) {
                try {
                    new Integer(str);
                } catch(Exception ex) {
            Class<Integer> claz = Integer.class;
            try {
                Constructor<Integer> con = claz.getConstructor(String.class);
                for(Class exClass : con.getExceptionTypes()) {
            } catch(NoSuchMethodException nsme) {

Similar Threads

  1. Replies: 2
    Last Post: 01-20-2014, 07:45 AM
  2. Replies: 24
    Last Post: 05-18-2009, 10:23 AM
  3. [SOLVED] [newbie] java.lang.NullPointerException
    By jon80 in forum New To Java
    Replies: 5
    Last Post: 05-07-2009, 04:19 PM
  4. Newbie - Robot Class
    By drasgear in forum New To Java
    Replies: 2
    Last Post: 11-14-2008, 04:46 PM
  5. Replies: 1
    Last Post: 08-02-2007, 04:07 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts