September 07, 2010, 04:15:07 AM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
  Home Help Media Affiliates Login Register  
Pages: [1]   Go Down
  Print  
Author Topic: How to define a construtor at runtime that takes N parameters (N= 1,2,...n)  (Read 1166 times)
0 Members and 1 Guest are viewing this topic.
JavaLearner
Member
*

Reputation: 0
Offline Offline
Posts: 34
Referrals: 0

Awards
« on: July 05, 2009, 06:08:30 AM »

Hi All,

I Have two class A and B.
I am reading a int number N where n belongs to natural number so n can be 1, 2, 3, 4, ......N and so on

Now in class A, i want to call the construtor of class B that takes N parameters.


class B
{
public B()
{
S.O.P("B"); /// SOP is for system.out.println

}

public B(String 1st)
{
S.O.P ("construtor with 1 parameter"); /// SOP is for system.out.println

}

public B(String 1st, String 2nd)
{
S.O.P("construtor with 2 parameters"); /// SOP is for system.out.println
}
}


in class B i can define construtor for 10 parameters or for 20 parameters but what if number of parameters can be more and if I am getting this number of parameters at runtime, then how can i define a construtor in class B with that number of parameters

I am reading an int input N in class A and want to call a construtor of class B that takes N parameters.
where n belongs to natural number so n = 1 2 3 4 .......infinitive.


class A
{
public static void main(String arg[])
{
System.out.println("Number of arguments for class B construtor " + arg[0]);

/// below step is problem what code i should use here to get a construtor of B that takes N parameters
// B b = new B(String str1, String str2, String str3 .......and so on this number of arguments must be equal to N or arg[0] value)

}



is there any way to define the constructor of any Class at runtime with the desired number of parameters?
i cant define construtor of class B manually for all values of n.

you can reply on mailofpravin@gmail.com too
Logged
Javaforums.net :: a community about Java software development.
« on: July 05, 2009, 06:08:30 AM »

Your Ad Here
 Logged
jimmy5410
Junior Member
*

Reputation: 0
Offline Offline
Posts: 3
Referrals: 0

Awards
« Reply #1 on: September 05, 2009, 09:22:20 PM »

Code:
public class B {
    public B(String... args) {
        System.out.println(args.length + " args!");
    }
}
It's... MAGIC!
Logged
Javaforums.net :: a community about Java software development.
   

Your Ad Here
 Logged
Pages: [1]   Go Up
  Print  
 
Jump to:  

Your Ad Here
Powered by MySQL Powered by PHP Powered by SMF 1.1.10 | SMF © 2006-2009, Simple Machines LLC
TinyPortal v0.9.8 © Bloc
Valid XHTML 1.0! Valid CSS!
Page created in 0.19 seconds with 35 queries.

Google visited last this page Yesterday at 08:36:21 AM