Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7447699
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T12:41:50+00:00 2026-05-29T12:41:50+00:00

With Java reflection, one can get a constructor through getConstructor(klass, args) . However, when

  • 0

With Java reflection, one can get a constructor through getConstructor(klass, args).

However, when we pass as args a derived class of the class specified in the constructor signature, it fails. How to overcome this issue?

For example,

HashSet.class.getConstructor(new Class[]{ HashSet.class });

fails. While

HashSet.class.getConstructor(new Class[]{ Collection.class });

succeeds.

I am looking for something that could easily be used in clojure. Therefore, I would prefer to have something out of the box and not having to add user-defined functions.

Any idea, how to solve this issue?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T12:41:53+00:00Added an answer on May 29, 2026 at 12:41 pm

    Building on the answers of esaj and T.J. Crowder:

    The following returns a seq of constructors for the given class which are (1) callable with the specified argument types and (2) optimal in the sense that their declared parameter types are removed by a minimal number of steps up the inheritance ladder from the specified argument types. (Thus an exact match will always be returned alone; if there are two constructors which require casting from some of the specified argument types to their grandparent types, and there is no closer match, they will both be returned; if there are no matching constructors at all, nil will be returned.) Primitive argument types may be specified as symbols or keywords (i.e. 'int / :int). Finally, primitive types are considered equivalent to their boxed counterparts.

    Example:

    user> (find-best-constructors java.util.HashSet [:int :float])
    (#<Constructor public java.util.HashSet(int,float)>)
    user> (find-best-constructors java.util.HashSet [java.util.HashSet])
    (#<Constructor public java.util.HashSet(java.util.Collection)>)
    user> (find-best-constructors java.util.HashSet [Integer])
    (#<Constructor public java.util.HashSet(int)>)
    

    One might want to permit widening numeric conversions; that could be done e.g. by adding Integer -> Long etc. mappings to convm and tweaking the if condition in count-steps below.

    Here’s the code:

    (defn find-best-constructors [klass args]
            (let [keym {:boolean Boolean/TYPE
                        :byte    Byte/TYPE
                        :double  Double/TYPE
                        :float   Float/TYPE
                        :int     Integer/TYPE
                        :long    Long/TYPE
                        :short   Short/TYPE}
                  args (->> args
                            (map #(if (class? %) % (keyword %)))
                            (map #(keym % %)))
                  prims (map keym [:boolean :byte :double :float :int :long :short])
                  boxed [Boolean Byte Double Float Integer Long Short]
                  convm (zipmap (concat prims boxed) (concat boxed prims))
                  ctors (->> (.getConstructors klass)
                             (filter #(== (count args) (count (.getParameterTypes %))))
                             (filter #(every? (fn [[pt a]]
                                                (or (.isAssignableFrom pt a)
                                                    (if-let [pt* (convm pt)]
                                                      (.isAssignableFrom pt* a))))
                                              (zipmap (.getParameterTypes %) args))))]
              (when (seq ctors)
                (let [count-steps (fn count-steps [pt a]
                                    (loop [ks #{a} cnt 0]
                                      (if (or (ks pt) (ks (convm pt)))
                                        cnt
                                        (recur (set (mapcat parents ks)) (inc cnt)))))
                      steps (map (fn [ctor]
                                   (map count-steps (.getParameterTypes ctor) args))
                                 ctors)
                      m (zipmap steps ctors)
                      min-steps (->> steps
                                     (apply min-key (partial apply max))
                                     (apply max))]
                  (->> m
                       (filter (comp #{min-steps} (partial apply max) key))
                       vals)))))
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

As we all know, String is immutable in java. however, one can change it
through java reflection how to check that method name is in camelCase? e.g. import
By using java reflection, we can easily know if an object is an array.
How can I print the type of a generic java type? Reflection? Any tricks?
I know in Java we can create an instance of a Class by new
Using Java Reflection, is it possible to get the name of a local variable?
We can use reflection to get method names as follows: object Foo { def
I'm using reflection to map getters from one class to setters in another i.e.
How could I access protected class by means of reflection? This one does not
I posted a question last night about Java Reflection and am discovering compiler warnings

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.