Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Numerous data members

Status
Not open for further replies.

sm43

Programmer
Dec 1, 2002
155
US
If a class has a lot of data members, is there a way a quick way to write the accessors, mutators and parametrized constructor (constructor that initializes data members based on values passed to it) that will take far less amount of code, and is not too elaborate..


Thanks..

Saad
 
You'll probably always need the getters and setters (accessor/mutators)....an IDE like Forte will generate them for you to save some typing. Jeremy Nicholson, Director of a UK-based Java and Data Warehousing consultancy
 
You can even do it with a little perl
Code:
#!/usr/bin/perl -w

my @vars;

while(<DATA>) {
  if( /(\S+)\s+(\S+)\s*;/ ) {
    push @vars, { type => $1, name => $2 };
  }
  print;
}

print << &quot;EOF&quot;;
  public CONSTRUCTOR(
${\(&args())}
  )
  {
${\(&init())}
  }

${\(&sets())}
${\(&gets())}
EOF

sub args {
  return join(&quot;,\n&quot;, map { &quot;    $_->{type} $_->{name}&quot; } @vars );
}

sub init {
  return join(&quot;\n&quot;, map { &quot;    this.$_->{name} = $_->{name};&quot; } @vars );
}
sub sets {
  return join(&quot;\n&quot;, map {
    &quot;  public void set&quot;.ucfirst($_->{name}).&quot;($_->{type} $_->{name}) { this.$_->{name} = $_->{name}; }&quot; } @vars );
}
sub gets {
  return join(&quot;\n&quot;, map {
    &quot;  public $_->{type} get&quot;.ucfirst($_->{name}).&quot;() { return $_->{name}; }&quot; } @vars );
}

__END__

public int x;
public Integer y;
Cheers, Neil :)
 
wow I didn't understand that perl thing but thanks..

Saad
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top