Search Results

Search found 456 results on 19 pages for 'getter'.

Page 1/19 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Calling "Base-Getter" in Overriding Getter of Property

    - by scherand
    I have a base class "Parent" like this: using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Parent { private int parentVirtualInt = -1; public virtual int VirtualProperty { get { return parentVirtualInt; } set { if(parentVirtualInt != value) { parentVirtualInt = value; } } } } } and a child class like this: using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Child : Parent { public override int VirtualProperty { get { if(base.VirtualProperty > 0) { throw new ApplicationException("Dummy Ex"); } return base.VirtualProperty; } set { if(base.VirtualProperty != value) { base.VirtualProperty = value; } } } } } Note that the getter in Child is calling the getter of Parent (or at least this is what I intend). I now use the "Child" class by instantiating it, assigning a value (let's say 4) to its VirtualProperty and then reading the property again. Child c = new Child(); c.VirtualProperty = 4; Console.Out.WriteLine("Child.VirtualProperty: " + c.VirtualProperty); When I run this, I obviously get an ApplicationException saying "Dummy Ex". But if I set a breakpoint on the line if(base.VirtualProperty > 0) in Child and check the value of base.VirtualProperty (by hovering the mouse over it) before the exception can be thrown (I assume(d)), I already get the Exception. From this I convey that the statement base.VirtualProperty in the "Child-Getter calls itself"; kind of. What I would like to achieve is the same behavior I get when I change the definition of parentVirutalInt (in Parent) to protected and use base.parentVirtualInt in the Getter of Child instead of base.VirtualProperty. And I don't yet see why this is not working. Can anybody shed some light on this? I feel that overridden properties behave differently than overridden methods? By the way: I am doing something very similar with subclassing a class I do not have any control over (this is the main reason why my "workaround" is not an option). Kind regards

    Read the article

  • Sent Item code in java

    - by Farhan Khan
    I need urgent help, if any one can resolve my issue it will be very highly appriciated. I have create a SMS composer on jAVA netbians its on urdu language. the probelm is its not saving sent sms on Sent items.. i have tried my best to make the code but failed. Tomorrow is my last day to present the code on university please help me please below is the code that i have made till now. Please any one.... /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package newSms; import javax.microedition.io.Connector; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.wireless.messaging.MessageConnection; import javax.wireless.messaging.TextMessage; import org.netbeans.microedition.util.SimpleCancellableTask; /** * @author AHTISHAM */ public class composeurdu extends MIDlet implements CommandListener, ItemCommandListener, ItemStateListener { private boolean midletPaused = false; private boolean isUrdu; String numb=" "; Alert alert; //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0| private Form form; private TextField number; private TextField textUrdu; private StringItem stringItem; private StringItem send; private Command exit; private Command sendMesg; private Command add; private Command urdu; private Command select; private SimpleCancellableTask task; //</editor-fold>//GEN-END:|fields|0| MessageConnection clientConn; private Display display; public composeurdu() { display = Display.getDisplay(this); } private void showMessage(){ display=Display.getDisplay(this); //numb=number.getString(); if(number.getString().length()==0 || textUrdu.getString().length()==0){ Alert alert=new Alert("error "); alert.setString(" Enter phone number"); alert.setTimeout(5000); display.setCurrent(alert); } else if(number.getString().length()>11){ Alert alert=new Alert("error "); alert.setString("invalid number"); alert.setTimeout(5000); display.setCurrent(alert); } else{ Alert alert=new Alert("error "); alert.setString("success"); alert.setTimeout(5000); display.setCurrent(alert); } } void showMessage(String message, Displayable displayable) { Alert alert = new Alert(""); alert.setTitle("Error"); alert.setString(message); alert.setType(AlertType.ERROR); alert.setTimeout(5000); display.setCurrent(alert, displayable); } //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0| //</editor-fold>//GEN-END:|methods|0| //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize /** * Initializes the application. It is called only once when the MIDlet is * started. The method is called before the * <code>startMIDlet</code> method. */ private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize // write pre-initialize user code here //GEN-LINE:|0-initialize|1|0-postInitialize // write post-initialize user code here }//GEN-BEGIN:|0-initialize|2| //</editor-fold>//GEN-END:|0-initialize|2| //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction /** * Performs an action assigned to the Mobile Device - MIDlet Started point. */ public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction // write pre-action user code here switchDisplayable(null, getForm());//GEN-LINE:|3-startMIDlet|1|3-postAction // write post-action user code here form.setCommandListener(this); form.setItemStateListener(this); }//GEN-BEGIN:|3-startMIDlet|2| //</editor-fold>//GEN-END:|3-startMIDlet|2| //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction /** * Performs an action assigned to the Mobile Device - MIDlet Resumed point. */ public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction // write pre-action user code here //GEN-LINE:|4-resumeMIDlet|1|4-postAction // write post-action user code here }//GEN-BEGIN:|4-resumeMIDlet|2| //</editor-fold>//GEN-END:|4-resumeMIDlet|2| //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch /** * Switches a current displayable in a display. The * <code>display</code> instance is taken from * <code>getDisplay</code> method. This method is used by all actions in the * design for switching displayable. * * @param alert the Alert which is temporarily set to the display; if * <code>null</code>, then * <code>nextDisplayable</code> is set immediately * @param nextDisplayable the Displayable to be set */ public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch // write pre-switch user code here Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch if (alert == null) { display.setCurrent(nextDisplayable); } else { display.setCurrent(alert, nextDisplayable); }//GEN-END:|5-switchDisplayable|1|5-postSwitch // write post-switch user code here }//GEN-BEGIN:|5-switchDisplayable|2| //</editor-fold>//GEN-END:|5-switchDisplayable|2| //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction /** * Called by a system to indicated that a command has been invoked on a * particular displayable. * * @param command the Command that was invoked * @param displayable the Displayable where the command was invoked */ public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction // write pre-action user code here if (displayable == form) {//GEN-BEGIN:|7-commandAction|1|16-preAction if (command == exit) {//GEN-END:|7-commandAction|1|16-preAction // write pre-action user code here exitMIDlet();//GEN-LINE:|7-commandAction|2|16-postAction // write post-action user code here } else if (command == sendMesg) {//GEN-LINE:|7-commandAction|3|18-preAction // write pre-action user code here String mno=number.getString(); String msg=textUrdu.getString(); if(mno.equals("")) { alert = new Alert("Alert"); alert.setString("Enter Mobile Number!!!"); alert.setTimeout(2000); display.setCurrent(alert); } else { try { clientConn=(MessageConnection)Connector.open("sms://"+mno); } catch(Exception e) { alert = new Alert("Alert"); alert.setString("Unable to connect to Station because of network problem"); alert.setTimeout(2000); display.setCurrent(alert); } try { TextMessage textmessage = (TextMessage) clientConn.newMessage(MessageConnection.TEXT_MESSAGE); textmessage.setAddress("sms://"+mno); textmessage.setPayloadText(msg); clientConn.send(textmessage); } catch(Exception e) { Alert alert=new Alert("Alert","",null,AlertType.INFO); alert.setTimeout(Alert.FOREVER); alert.setString("Unable to send"); display.setCurrent(alert); } } //GEN-LINE:|7-commandAction|4|18-postAction // write post-action user code here }//GEN-BEGIN:|7-commandAction|5|7-postCommandAction }//GEN-END:|7-commandAction|5|7-postCommandAction // write post-action user code here }//GEN-BEGIN:|7-commandAction|6| //</editor-fold>//GEN-END:|7-commandAction|6| //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Items ">//GEN-BEGIN:|8-itemCommandAction|0|8-preItemCommandAction /** * Called by a system to indicated that a command has been invoked on a * particular item. * * @param command the Command that was invoked * @param displayable the Item where the command was invoked */ public void commandAction(Command command, Item item) {//GEN-END:|8-itemCommandAction|0|8-preItemCommandAction // write pre-action user code here if (item == number) {//GEN-BEGIN:|8-itemCommandAction|1|21-preAction if (command == add) {//GEN-END:|8-itemCommandAction|1|21-preAction // write pre-action user code here //GEN-LINE:|8-itemCommandAction|2|21-postAction // write post-action user code here }//GEN-BEGIN:|8-itemCommandAction|3|28-preAction } else if (item == send) { if (command == select) {//GEN-END:|8-itemCommandAction|3|28-preAction // write pre-action user code here //GEN-LINE:|8-itemCommandAction|4|28-postAction // write post-action user code here }//GEN-BEGIN:|8-itemCommandAction|5|24-preAction } else if (item == textUrdu) { if (command == urdu) {//GEN-END:|8-itemCommandAction|5|24-preAction // write pre-action user code here if (isUrdu) isUrdu = false; else { isUrdu = true; TextField tf = (TextField)item; } //GEN-LINE:|8-itemCommandAction|6|24-postAction // write post-action user code here }//GEN-BEGIN:|8-itemCommandAction|7|8-postItemCommandAction }//GEN-END:|8-itemCommandAction|7|8-postItemCommandAction // write post-action user code here }//GEN-BEGIN:|8-itemCommandAction|8| //</editor-fold>//GEN-END:|8-itemCommandAction|8| //<editor-fold defaultstate="collapsed" desc=" Generated Getter: form ">//GEN-BEGIN:|14-getter|0|14-preInit /** * Returns an initialized instance of form component. * * @return the initialized component instance */ public Form getForm() { if (form == null) {//GEN-END:|14-getter|0|14-preInit // write pre-init user code here form = new Form("form", new Item[]{getNumber(), getTextUrdu(), getStringItem(), getSend()});//GEN-BEGIN:|14-getter|1|14-postInit form.addCommand(getExit()); form.addCommand(getSendMesg()); form.setCommandListener(this);//GEN-END:|14-getter|1|14-postInit // write post-init user code here form.setItemStateListener(this); // form.setCommandListener(this); }//GEN-BEGIN:|14-getter|2| return form; } //</editor-fold>//GEN-END:|14-getter|2| //<editor-fold defaultstate="collapsed" desc=" Generated Getter: number ">//GEN-BEGIN:|19-getter|0|19-preInit /** * Returns an initialized instance of number component. * * @return the initialized component instance */ public TextField getNumber() { if (number == null) {//GEN-END:|19-getter|0|19-preInit // write pre-init user code here number = new TextField("Number ", null, 11, TextField.PHONENUMBER);//GEN-BEGIN:|19-getter|1|19-postInit number.addCommand(getAdd()); number.setItemCommandListener(this); number.setDefaultCommand(getAdd());//GEN-END:|19-getter|1|19-postInit // write post-init user code here }//GEN-BEGIN:|19-getter|2| return number; } //</editor-fold>//GEN-END:|19-getter|2| //<editor-fold defaultstate="collapsed" desc=" Generated Getter: textUrdu ">//GEN-BEGIN:|22-getter|0|22-preInit /** * Returns an initialized instance of textUrdu component. * * @return the initialized component instance */ public TextField getTextUrdu() { if (textUrdu == null) {//GEN-END:|22-getter|0|22-preInit // write pre-init user code here textUrdu = new TextField("Message", null, 2000, TextField.ANY);//GEN-BEGIN:|22-getter|1|22-postInit textUrdu.addCommand(getUrdu()); textUrdu.setItemCommandListener(this);//GEN-END:|22-getter|1|22-postInit // write post-init user code here }//GEN-BEGIN:|22-getter|2| return textUrdu; } //</editor-fold>//GEN-END:|22-getter|2| //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exit ">//GEN-BEGIN:|15-getter|0|15-preInit /** * Returns an initialized instance of exit component. * * @return the initialized component instance */ public Command getExit() { if (exit == null) {//GEN-END:|15-getter|0|15-preInit // write pre-init user code here exit = new Command("Exit", Command.EXIT, 0);//GEN-LINE:|15-getter|1|15-postInit // write post-init user code here }//GEN-BEGIN:|15-getter|2| return exit; } //</editor-fold>//GEN-END:|15-getter|2| //<editor-fold defaultstate="collapsed" desc=" Generated Getter: sendMesg ">//GEN-BEGIN:|17-getter|0|17-preInit /** * Returns an initialized instance of sendMesg component. * * @return the initialized component instance */ public Command getSendMesg() { if (sendMesg == null) {//GEN-END:|17-getter|0|17-preInit // write pre-init user code here sendMesg = new Command("send", Command.OK, 0);//GEN-LINE:|17-getter|1|17-postInit // write post-init user code here }//GEN-BEGIN:|17-getter|2| return sendMesg; } //</editor-fold>//GEN-END:|17-getter|2| //<editor-fold defaultstate="collapsed" desc=" Generated Getter: add ">//GEN-BEGIN:|20-getter|0|20-preInit /** * Returns an initialized instance of add component. * * @return the initialized component instance */ public Command getAdd() { if (add == null) {//GEN-END:|20-getter|0|20-preInit // write pre-init user code here add = new Command("add", Command.OK, 0);//GEN-LINE:|20-getter|1|20-postInit // write post-init user code here }//GEN-BEGIN:|20-getter|2| return add; } //</editor-fold>//GEN-END:|20-getter|2| //<editor-fold defaultstate="collapsed" desc=" Generated Getter: urdu ">//GEN-BEGIN:|23-getter|0|23-preInit /** * Returns an initialized instance of urdu component. * * @return the initialized component instance */ public Command getUrdu() { if (urdu == null) {//GEN-END:|23-getter|0|23-preInit // write pre-init user code here urdu = new Command("urdu", Command.OK, 0);//GEN-LINE:|23-getter|1|23-postInit // write post-init user code here }//GEN-BEGIN:|23-getter|2| return urdu; } //</editor-fold>//GEN-END:|23-getter|2| //<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringItem ">//GEN-BEGIN:|25-getter|0|25-preInit /** * Returns an initialized instance of stringItem component. * * @return the initialized component instance */ public StringItem getStringItem() { if (stringItem == null) {//GEN-END:|25-getter|0|25-preInit // write pre-init user code here stringItem = new StringItem("string", null);//GEN-LINE:|25-getter|1|25-postInit // write post-init user code here }//GEN-BEGIN:|25-getter|2| return stringItem; } //</editor-fold>//GEN-END:|25-getter|2| //</editor-fold> //<editor-fold defaultstate="collapsed" desc=" Generated Getter: send ">//GEN-BEGIN:|26-getter|0|26-preInit /** * Returns an initialized instance of send component. * * @return the initialized component instance */ public StringItem getSend() { if (send == null) {//GEN-END:|26-getter|0|26-preInit // write pre-init user code here send = new StringItem("", "send", Item.BUTTON);//GEN-BEGIN:|26-getter|1|26-postInit send.addCommand(getSelect()); send.setItemCommandListener(this); send.setDefaultCommand(getSelect());//GEN-END:|26-getter|1|26-postInit // write post-init user code here }//GEN-BEGIN:|26-getter|2| return send; } //</editor-fold>//GEN-END:|26-getter|2| //<editor-fold defaultstate="collapsed" desc=" Generated Getter: select ">//GEN-BEGIN:|27-getter|0|27-preInit /** * Returns an initialized instance of select component. * * @return the initialized component instance */ public Command getSelect() { if (select == null) {//GEN-END:|27-getter|0|27-preInit // write pre-init user code here select = new Command("select", Command.OK, 0);//GEN-LINE:|27-getter|1|27-postInit // write post-init user code here }//GEN-BEGIN:|27-getter|2| return select; } //</editor-fold>//GEN-END:|27-getter|2| //<editor-fold defaultstate="collapsed" desc=" Generated Getter: task ">//GEN-BEGIN:|40-getter|0|40-preInit /** * Returns an initialized instance of task component. * * @return the initialized component instance */ public SimpleCancellableTask getTask() { if (task == null) {//GEN-END:|40-getter|0|40-preInit // write pre-init user code here task = new SimpleCancellableTask();//GEN-BEGIN:|40-getter|1|40-execute task.setExecutable(new org.netbeans.microedition.util.Executable() { public void execute() throws Exception {//GEN-END:|40-getter|1|40-execute // write task-execution user code here }//GEN-BEGIN:|40-getter|2|40-postInit });//GEN-END:|40-getter|2|40-postInit // write post-init user code here }//GEN-BEGIN:|40-getter|3| return task; } //</editor-fold>//GEN-END:|40-getter|3| /** * Returns a display instance. * @return the display instance. */ public Display getDisplay () { return Display.getDisplay(this); } /** * Exits MIDlet. */ public void exitMIDlet() { switchDisplayable (null, null); destroyApp(true); notifyDestroyed(); } /** * Called when MIDlet is started. * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet. */ public void startApp() { startMIDlet(); display.setCurrent(form); } /** * Called when MIDlet is paused. */ public void pauseApp() { midletPaused = true; } /** * Called to signal the MIDlet to terminate. * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released. */ public void destroyApp(boolean unconditional) { } public void itemStateChanged(Item item) { if (item == textUrdu) { if (isUrdu) { stringItem.setText("urdu"); TextField tf = (TextField)item; String s = tf.getString(); char ch = s.charAt(s.length() - 1); s = s.substring(0, s.length() - 1); ch = Urdu.ToUrdu(ch); s = s + String.valueOf(ch); tf.setString(""); tf.setString(s); }//end if throw new UnsupportedOperationException("Not supported yet."); } } }

    Read the article

  • Best way of invoking getter by reflection

    - by Javi
    Hello, I need to get the value of a field with a specific annotation, So with reflection I am able to get this Field Object. The problem is that this field will be always private though I know in advance it will always have a getter method. I know that I can use setAccesible(true) and get its value (when there is no PermissionManager), though I prefer to invoke its getter method. I know that I could look for the method by looking for "get+fieldName" (though I know for example for boolean fields are sometimes named as "is+fieldName"). I wonder if there is a better way to invoke this getter (many frameworks use getters/setters to access the attributes so maybe they do in another way). Thanks

    Read the article

  • Objective-C property getter

    - by Daniel
    What is technically wrong with the following: @property(nonatomic, assign) NSUInteger timestamp; @property(nonatomic, readonly, getter = timestamp) NSUInteger startTime; @property(nonatomic, assign) NSUInteger endTime; I am sure I can find a better way to organise this, but this is what I ended up with at one point in my project and I noticed that accessing the startTime property always returned 0, even when the timestamp property was set to a correct timestamp. It seems having set the getter of startTime to an existing property (timestamp), it is not forwarding the value of timestamp when I do: event.startTime => 0 event.timestamp => 1340920893 All these are timestamps by the way. Just a reminder, I know the above should have happened in my project but I don't understand why accessing startTime doesn't forward onto timestamp property. UPDATE In my implementation I am synthesising all of these properties: @synthesize timestamp, endTime, startTime; Please check an example object to use that demonstrates this at my gist on GitHub: https://gist.github.com/3013951

    Read the article

  • Objective C - Custom Getter with inheritance

    - by anhdat
    Recently I have worked with Core Data. When I want to set a default value for some fields, I came up with this problem: So I made a simple represent: We have 2 class Parent and Child, in which Child inherit from Parent. // Parent.h @interface Parent : NSObject @property (strong, nonatomic) NSString *lastName; // Child.h @interface Child : Parent In Parent class, I made a custom getter to set a default value when nothing is set: // Parent.h - (NSString *)lastName { if (_lastName) { return _lastName; } else { return @"Parent Default Name"; } } But I cannot make a custom default value for the field "name" which Child inherits from its Parent. // Child.h @implementation Child - (NSString *)lastname { if (super.lastName) { return super.lastName; } else { return @"Child Default Name"; } } Apparently, this method is never called. So my question here is: How can I set a custom getter for the field the Child class inherits from Parent without define an overriding property?

    Read the article

  • Why setter method when getter method enough in PHP OOP

    - by phphunger
    I am practicing OOP with PHP, and I am struck at setter and getter methods. I can directly access the class properties and methods with getter method then what's the use of setter method? See my example. <?php class MyClass{ public $classVar = "Its a class variable"; public function Getter(){ return $this -> classVar; } } $obj = new MyClass; echo $obj -> Getter(); ?>

    Read the article

  • Objective-C getter/ setter question

    - by pic-o-matic
    Hi, im trying to works my way trough an Objective-C tutorial. In the book there is this example: @interface { int width; int height; XYPoint *origin; } @property int width, height; I though, hey there's no getter/setter for the XYPoint object. The code does work though. Now i'm going maybe to answer my own question :). I thinks its because "origin" is a pointer already, and whats happening under the hood with "width" and "height", is that there is going te be created a pointer to them.. Am i right, or am i talking BS :) ??

    Read the article

  • How to use a getter with a nullable?

    - by Desmond Lost
    I am reading a bunch of queries from a database. I had an issue with the queries not closing, so I added a CommandTimeout. Now, the individual queries read from the config file each time they are run. How would I make the code cache the int from the config file only once using a static nullable and getter. I was thinking of doing something along the lines of: static int? var; get{ var = null; if (var.HasValue) ...(i dont know how to complete the rest) My actual code: private object ExecuteQuery(string dbConnStr, bool fixIt) { object result = false; using (SqlConnection connection = new SqlConnection(dbConnStr)) { connection.Open(); using (SqlCommand sqlCmd = new SqlCommand()) { AddSQLParms(sqlCmd); sqlCmd.CommandTimeout = 30; sqlCmd.CommandText = _cmdText; sqlCmd.Connection = connection; sqlCmd.CommandType = System.Data.CommandType.Text; sqlCmd.ExecuteNonQuery(); } connection.Close(); } return result; }}

    Read the article

  • Getter/setter on javascript array?

    - by Martin Hansen
    Is there a way to get a get/set behaviour on an array? I imagine something like this: var arr = ['one', 'two', 'three']; var _arr = new Array(); for (var i=0; i < arr.length; i++) { arr[i].defineGetter('value', function(index) { //Do something return _arr[index]; }); arr[i].defineSetter('value', function(index, val) { //Do something _arr[index] = val; }); };

    Read the article

  • C# - What should I do when every inherited class needs getter from base class, but setter only for O

    - by msfanboy
    Hello, I have a abstract class called WizardViewModelBase. All my WizardXXXViewModel classes inherit from the base abstract class. The base has a property with a getter. Every sub class needs and overrides that string property as its the DisplayName of the ViewModel. Only ONE ViewModel called WizardTimeTableWeekViewModel needs a setter because I have to set wether the ViewModel is a timetable for week A or week B. Using 2 ViewModels like WizardTimeTableWeekAViewModel and WizardTimeTableWeekBViewModel would be redundant. I do not want to override the setter in all other classes as they do not need a setter. Can I somehow tell the sub class it needs not to override the setter? Or any other suggestion? With interfaces I would be free to use getter or setter but having many empty setter properties is not an option for me.

    Read the article

  • Getter and Setter vs. Builder strategy

    - by Extrakun
    I was reading a JavaWorld's article on Getter and Setter where the basic premise is that getters expose internal content of an object, hence tightening coupling, and go on to provide examples using builder objects. I was rather leery of abolishing getter/setter but on second reading of the article, see to quite like the idea. However, sometimes I just need one cruical element of an entity class, such as the user's id and writing one whole class just to extract that cruical element seems like overkill. It also implies that for different view, a different type of importer/exporter must be implemented (or the whole data of the class to be exported out, thus resulting in waste). Usually I tend towards filtering the result of a getter - for example, if I need to output the price of a product in different currency, I would code it as: return CurrencyOutput::convertTo($product->price(), 'USD'); This is with the understanding that the raw output of a getter is not necessary the final result to be pushed onto a screen or a database. Is getter/setter really as bad as it is protrayed to be? When should one adopt a builder strategy, or a 'get the result and filter it' approach? How do you avoid having a class needing to know about every other objects if you are not using getter/setter?

    Read the article

  • prevent the designer from calling a getter (VS 2008, WinForms)

    - by LLEA
    hi, I have a simple UserControl containing a ComboBox which is empty at first. The setter for that CB adds items to it and the getter returns the selected item. When adding this UC to a Form, the designer automatically calls the getter for the CB which is empty. The method to fill up the CB with items is called later. I can think of one or two ways to bypass this problem by "messing around" in the code. But before I start that I'd like to ask you if there is a way to stop the designer from calling the getter method. Maybe with a attribute similar to Browsable or Bindable? thx

    Read the article

  • Between a jsf page and a managed bean, why the getter method is called twice

    - by Bariscan
    Hi, I have a jsf page with a form has an outputtext in it. The value of outputtext component is called from a backing bean (or managed bean). I know when I code it as #{MyBean.myString} Jsf rename it and calls getMyString() method. However the wierd thing is, when I put a breakpoint to the getter method of this component, I see it is called twice during the page is being rendered. The outputtext is in a h:form, and it is the only component wich is bind to a backingbean. I mean, it is so wierd that jsf should get the value when it first come to the getter method, however it needs to go to the getter method twice. Can you explain what is the reason of this behaviour in jsf? Any help would be appreciated, Best wishes, Baris

    Read the article

  • Getter and Setter - POJO object - Problem with input data in Struts2

    - by andreimladin
    I have a problem with setter and getter method in struts2. I have a form : ... + all input fields of job/ and action: (addJob is mapped at this action) public class InsertJobAction extends ActionSupport{ ... private Job job = null; public String execute(){ jobService.insert(job); //here job is not null; that is ok } getter and setter for job } this action works correctly; I have a similar form and action, but the input fields from thisform are less than first form; The problem is here: in execute() of the second action job is null. Why?? Does depend it of fields noumber ?? I have 2 constructors in my Job class one with no params, and one with all params for every field of class; I made debug with Log4j ...and in first case there arrives in Job constructor in the second not. Why??When it calls constructor??? When are called the setter and getter methodsb, before or after execute() method??? And when i have a form with input data?? Are called setter methods before execute() method? I'm very confusely because in a case it works without problems, but in the second case it doesn't Thanks, Andrew

    Read the article

  • Value object getter

    - by sarah xia
    Hi, I've got a value object, which stores info for example amount. The getAmount() getter returns amount in cents. However in various places, we need to get amount in dollar. There are 2 approaches I can think of: write a convert method and place it in a utility class. add a getAmountInDollar() getter in the value object. I prefer the second approach. What do you think? What are pros and cons of both approaches?

    Read the article

  • Java singleton VO class implementing serializable, having default values using getter methods

    - by user309281
    Hi All I have a J2SE application having user threads running in a separate JVM outside JBOSS server. During startup, J2SE invokes a EJB inside jboss, by passing a new object(singleton) of simple JAVA VO class having getter/setter methods. {The VO class is a singleton and implements serialiable(as mandated by EJB)}. EJB receives the object, reads all db configuration and uses the setter methods of new object to set all the values. It then returns back this updated object back to J2SE in the same remote call. After J2SE receives the object(singleton/serializable), if i invoke getter methods, I could see only default values set during object creation before EJB call, and not the values set by the EJB. Kindly throw some light on, why the received object from EJB does not see any updated values and how to rectify this. I believe it got to do with object initialization during deserialization. And i tried overriding readResolve() in the VO class, but of no help. With Regards, Krishna

    Read the article

  • Adding business logic to a domain class using a getter style method name

    - by Richard Paul
    I'm attempting to add a method to a grails domain class, e.g. class Item { String name String getReversedName() { name.reverse() } } When I attempt to load the application using grails console I get the following error: Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory':Invocation of init method failed; nested exception is org.hibernate.PropertyNotFoundException: Could not find a setter for property reversedName in class Item ... 18 more It looks like Hibernate is interpreting getReversedName() as a getter for a property, however in this case it is a derived field and hence should not be persisted. Obviously in my actual code the business logic I'm exposing is more complex but it isn't relevant to this question. I want to be able to call item.reversedName in my code/gsps. How can I provide property (getter) access to a method in a Grails domain class without Grails attempting to map it with Hibernate?

    Read the article

  • Getter/Setter from separate class file in Java

    - by Crystal
    I'm new to Java and for a HW assignment, we had to create a Person class that has a constructor, getter/setter for the attributes of firstName, lastName, phone. That is in a separate file from an old HW assignment (Person.java). Now we have to use that Person class in our new HW assignment (LoanApplication.java). So if one of the attributes is private Person client do I need to create getter/setters or a constructor again? Otherwise, how does each LoanApplicaiton instance know which Person attribute it is to go with? How does the JVM know that it can use the Person.class even though my LoanApplicaiton.class does not extend Person.class? Thanks.

    Read the article

  • Create a delegate from a property getter or setter method

    - by thecoop
    To create a delegate from a method you can use the compile-safe syntax: private int Method() { ... } // and create the delegate to Method... Func<int> d = Method; A property is a wrapper around a getter and setter method, and I want to create a delegate to a property getter method. Something like public int Prop { get; set; } Func<int> d = Prop; // or... Func<int> d = Prop_get; Which doesn't work, unfortunately. I have to create a separate lambda method, which seems unnecessary when the setter method matches the delegate signature anyway: Func<int> d = () => Prop; In order to use the delegate method directly, I have to use nasty reflection, which isn't compile-safe: // something like this, not tested... MethodInfo m = GetType().GetProperty("Prop").GetGetMethod(); Func<int> d = (Func<int>)Delegate.CreateDelegate(typeof(Func<int>), m); Is there any way of creating a delegate on a property getting method directly in a compile-safe way, similar to creating a delegate on a normal method at the top, without needing to use an intermediate lambda method?

    Read the article

  • Hibernate unable to instantiate default tuplizer - cannot find getter

    - by ZeldaPinwheel
    I'm trying to use Hibernate to persist a class that looks like this: public class Item implements Serializable, Comparable<Item> { // Item id private Integer id; // Description of item in inventory private String description; // Number of items described by this inventory item private int count; //Category item belongs to private String category; // Date item was purchased private GregorianCalendar purchaseDate; public Item() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public GregorianCalendar getPurchaseDate() { return purchaseDate; } public void setPurchasedate(GregorianCalendar purchaseDate) { this.purchaseDate = purchaseDate; } My Hibernate mapping file contains the following: <property name="puchaseDate" type="java.util.GregorianCalendar"> <column name="purchase_date"></column> </property> When I try to run, I get error messages indicating there is no getter function for the purchaseDate attribute: 577 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!) 577 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20 577 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false 592 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/home_inventory 592 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=root, password=****} 1078 [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: MySQL, version: 5.1.45 1078 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.12 ( Revision: ${bzr.revision-id} ) 1103 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQLDialect 1107 [main] INFO org.hibernate.engine.jdbc.JdbcSupportLoader - Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4 1109 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions) 1110 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) 1110 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled 1110 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled 1110 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15 1110 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled 1111 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled 1111 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled 1111 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto 1111 [main] INFO org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2 1111 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1 1111 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled 1111 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled 1111 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled 1112 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory 1113 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory 1113 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {} 1113 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled 1113 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled 1113 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled 1113 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory 1113 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled 1114 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled 1117 [main] INFO org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout 1118 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled 1118 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled 1118 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo 1118 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled 1118 [main] INFO org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): enabled 1151 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer] at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:110) at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:135) at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:80) at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:323) at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:475) at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:133) at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:84) at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:295) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1385) at service.HibernateSessionFactory.currentSession(HibernateSessionFactory.java:53) at service.ItemSvcHibImpl.generateReport(ItemSvcHibImpl.java:78) at service.test.ItemSvcTest.testGenerateReport(ItemSvcTest.java:226) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:164) at junit.framework.TestCase.runBare(TestCase.java:130) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:120) at junit.framework.TestSuite.runTest(TestSuite.java:230) at junit.framework.TestSuite.run(TestSuite.java:225) at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:107) ... 29 more Caused by: org.hibernate.PropertyNotFoundException: Could not find a getter for puchaseDate in class domain.Item at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:328) at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:321) at org.hibernate.mapping.Property.getGetter(Property.java:304) at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:299) at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:158) at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:77) ... 34 more I'm new to Hibernate, so I don't know all the ins and outs, but I do have the getter and setter for the purchaseDate attribute. I don't know what I'm missing here - does anyone else? Thanks!

    Read the article

  • .NET: Interface Problem VB.net Getter Only Interface

    - by snmcdonald
    Why does an interface override a class definition and violate class encapsulation? I have included two samples below, one in C# and one in VB.net? VB.net Module Module1 Sub Main() Dim testInterface As ITest = New TestMe Console.WriteLine(testInterface.Testable) ''// Prints False testInterface.Testable = True ''// Access to Private!!! Console.WriteLine(testInterface.Testable) ''// Prints True Dim testClass As TestMe = New TestMe Console.WriteLine(testClass.Testable) ''// Prints False ''//testClass.Testable = True ''// Compile Error Console.WriteLine(testClass.Testable) ''// Prints False End Sub End Module Public Class TestMe : Implements ITest Private m_testable As Boolean = False Public Property Testable As Boolean Implements ITest.Testable Get Return m_testable End Get Private Set(ByVal value As Boolean) m_testable = value End Set End Property End Class Interface ITest Property Testable As Boolean End Interface C# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace InterfaceCSTest { class Program { static void Main(string[] args) { ITest testInterface = new TestMe(); Console.WriteLine(testInterface.Testable); testInterface.Testable = true; Console.WriteLine(testInterface.Testable); TestMe testClass = new TestMe(); Console.WriteLine(testClass.Testable); //testClass.Testable = true; Console.WriteLine(testClass.Testable); } } class TestMe : ITest { private bool m_testable = false; public bool Testable { get { return m_testable; } private set { m_testable = value; } } } interface ITest { bool Testable { get; set; } } } More Specifically How do I implement a interface in VB.net that will allow for a private setter. For example in C# I can declare: class TestMe : ITest { private bool m_testable = false; public bool Testable { get { return m_testable; } private set //No Compile Error here! { m_testable = value; } } } interface ITest { bool Testable { get; } } However, if I declare an interface property as readonly in VB.net I cannot create a setter. If I create a VB.net interface as just a plain old property then interface declarations will violate my encapsulation. Public Class TestMe : Implements ITest Private m_testable As Boolean = False Public ReadOnly Property Testable As Boolean Implements ITest.Testable Get Return m_testable End Get Private Set(ByVal value As Boolean) ''//Compile Error m_testable = value End Set End Property End Class Interface ITest ReadOnly Property Testable As Boolean End Interface So my question is, how do I define a getter only Interface in VB.net with proper encapsulation? I figured the first example would have been the best method. However, it appears as if interface definitions overrule class definitions. So I tried to create a getter only (Readonly) property like in C# but it does not work for VB.net. Maybe this is just a limitation of the language?

    Read the article

  • Java constructor with large arguments or Java bean getter/setter approach

    - by deelo55
    Hi, I can't decide which approach is better for creating objects with a large number of fields (10+) (all mandatory) the constructor approach of the getter/setter. Constructor at least you enforce that all the fields are set. Java Beans easier to see which variables are being set instead of a huge list. The builder pattern DOES NOT seem suitable here as all the fields are mandatory and the builder requires you put all mandatory parameters in the builder constructor. Thanks, D

    Read the article

  • Flex 4: Getter getting before setter sets

    - by Steve
    I've created an AS class to use as a data model, shown here: package { import mx.controls.Alert; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.rpc.http.HTTPService; public class Model { private var xmlService:HTTPService; private var _xml:XML; private var xmlChanged:Boolean = false; public function Model() { } public function loadXML(url:String):void { xmlService = new HTTPService(); if (!url) xmlService.url = "DATAPOINTS.xml"; else xmlService.url = url; xmlService.resultFormat = "e4x"; xmlService.addEventListener(ResultEvent.RESULT, setXML); xmlService.addEventListener(FaultEvent.FAULT, faultXML); xmlService.send(); } private function setXML(event:ResultEvent):void { xmlChanged = true; this._xml = event.result as XML; } private function faultXML(event:FaultEvent):void { Alert.show("RAF data could not be loaded."); } public function get xml():XML { return _xml; } } } And in my main application, I'm initiating the app and calling the loadXML function to get the XML: <fx:Script> <![CDATA[ import mx.containers.Form; import mx.containers.FormItem; import mx.containers.VBox; import mx.controls.Alert; import mx.controls.Button; import mx.controls.Label; import mx.controls.Text; import mx.controls.TextInput; import spark.components.NavigatorContent; private function init():void { var model:Model = new Model(); model.loadXML(null); var xml:XML = model.xml; } ]]> </fx:Script> The trouble I'm having is that the getter function is running before loadXML has finished, so the XML varible in my main app comes up undefined in stack traces. How do I put a condition in here somewhere that tells the getter to wait until the loadXML() function has finished before running?

    Read the article

  • Scala: can't write setter without getter?

    - by IttayD
    This works: class ButtonCountObserver { private var cnt = 0 // private field def count = cnt // reader method def count_=(newCount: Int) = cnt = newCount // writer method // ... } val b = new ButtonCountObserver b.count = 0 But this doesn't class ButtonCountObserver { private var cnt = 0 // private field def count_=(newCount: Int) = cnt = newCount // writer method // ... } val b = new ButtonCountObserver b.count = 0 I get: error: value count is not a member of ButtonCountObserver Is it possible to create a setter (with the syntactic sugar) without a getter?

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >