Search Results

Search found 356 results on 15 pages for 'getters'.

Page 12/15 | < Previous Page | 8 9 10 11 12 13 14 15  | Next Page >

  • @PrePersist with entity inheritance

    - by gerry
    I'm having some problems with inheritance and the @PrePersist annotation. My source code looks like the following: _the 'base' class with the annotated updateDates() method: @javax.persistence.Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class Base implements Serializable{ ... @Id @GeneratedValue protected Long id; ... @Column(nullable=false) @Temporal(TemporalType.TIMESTAMP) private Date creationDate; @Column(nullable=false) @Temporal(TemporalType.TIMESTAMP) private Date lastModificationDate; ... public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Date getLastModificationDate() { return lastModificationDate; } public void setLastModificationDate(Date lastModificationDate) { this.lastModificationDate = lastModificationDate; } ... @PrePersist protected void updateDates() { if (creationDate == null) { creationDate = new Date(); } lastModificationDate = new Date(); } } _ now the 'Child' class that should inherit all methods "and annotations" from the base class: @javax.persistence.Entity @NamedQueries({ @NamedQuery(name=Sensor.QUERY_FIND_ALL, query="SELECT s FROM Sensor s") }) public class Sensor extends Entity { ... // additional attributes @Column(nullable=false) protected String value; ... // additional getters, setters ... } If I store/persist instances of the Base class to the database, everything works fine. The dates are getting updated. But now, if I want to persist a child instance, the database throws the following exception: MySQLIntegrityConstraintViolationException: Column 'CREATIONDATE' cannot be null So, in my opinion, this is caused because in Child the method "@PrePersist protected void updateDates()" is not called/invoked before persisting the instances to the database. What is wrong with my code?

    Read the article

  • C# creating a Class, having objects as member variables? I think the objects are garbage collecte

    - by Bryan
    So I have a class that has the following member variables. I have get and set functions for every piece of data in this class. public class NavigationMesh { public Vector3 node; int weight; bool isWall; bool hasTreasure; public NavigationMesh(int x, int y, int z, bool setWall, bool setTreasure) { //default constructor //Console.WriteLine(x + " " + y + " " + z); node = new Vector3(x, y, z); //Console.WriteLine(node.X + " " + node.Y + " " + node.Z); isWall = setWall; hasTreasure = setTreasure; weight = 1; }// end constructor public float getX() { Console.WriteLine(node.X); return node.X; } public float getY() { Console.WriteLine(node.Y); return node.Y; } public float getZ() { Console.WriteLine(node.Z); return node.Z; } public bool getWall() { return isWall; } public void setWall(bool item) { isWall = item; } public bool getTreasure() { return hasTreasure; } public void setTreasure(bool item) { hasTreasure = item; } public int getWeight() { return weight; } }// end class In another class, I have a 2-Dim array that looks like this NavigationMesh[,] mesh; mesh = new NavigationMesh[502,502]; I use a double for loop to assign this, my problem is I cannot get the data I need out of the Vector3 node object after I create this object in my array with my "getters". I've tried making the Vector3 a static variable, however I think it refers to the last instance of the object. How do I keep all of these object in memory? I think there being garbage collected. Any thoughts?

    Read the article

  • Hibernate is persisting entity during flush when the entity has not changed

    - by Preston
    I'm having a problem where the entity manger is persisting an entity that I don't think has changed during the flush. I know the following code is the problem because if I comment it out the entity doesn't persist. In this code all I'm doing is loading the entity and calling some getters. Query qry = em.createNamedQuery("Clients.findByClientID"); qry.setParameter("clientID", clientID); Clients client = (Clients) qry.getSingleResult(); results.setFname(client.getFirstName()); results.setLname(client.getLastName()); ... return results; Later in a different method I do another namedQuery which causes the entity manger to flush. For some reason the client loaded above is persisted. The reason this is a problem is because in the middle of all this, there is some old code that is making some straight JDBC changes to the client. When the entity manger persists the changes made by the straight JDBC are lost. The theory we have at moment is that the entity manger is comparing the entity to the underlying record, sees that it's different, then persists it. Can someone explain or confirm the behavior we're seeing?

    Read the article

  • Insert data in an object to a database.

    - by paul
    I am facing the following design/implementation dilemma. I have a class Customer which is below with getters and setters. I would like to insert the value of the Customer into a "Customer" table of a database. But Customer has an address which is of type "Address". How do I go about inserting this field into the database?(I am using sqlite3). I thought of writing a separate table "Address(customerId,doorNo,city,state,country,pinCode)". But I am having second thoughts about generating the primary key(customerId) which should be same for both the "customer" and "Address" table. Sqlite3 faq states that I can do "Integer Primary Key" to use the field to generate an auto number. But if I do that in customer table, I would have to retrieve the same Id to be used in Address table. This kinda looks wrong to me :-?. There should be an elegant method to solve this. Any ideas would be much appreciated. Thanks in advance. import java.io.*; import java.sql.*; class Customer { private String id; private String name; private Address address; private Connection connection; private ResultSet resultSet; private PreparedStatement preparedStatement; public void insertToDatabase(){ } } class Address{ private String doorNumber; private String streetName; private String cityName; private String districtName; private String stateName; private String countryName; private long pinCode; }

    Read the article

  • how to get access to private members of nested class?

    - by macias
    Background: I have enclosed (parent) class E with nested class N with several instances of N in E. In the enclosed (parent) class I am doing some calculations and I am setting the values for each instance of nested class. Something like this: n1.field1 = ...; n1.field2 = ...; n1.field3 = ...; n2.field1 = ...; ... It is one big eval method (in parent class). My intention is -- since all calculations are in parent class (they cannot be done per nested instance because it would make code more complicated) -- make the setters only available to parent class and getters public. And now there is a problem: when I make the setters private, parent class cannot acces them when I make them public, everybody can change the values and C# does not have friend concept I cannot pass values in constructor because lazy evaluation mechanism is used (so the instances have to be created when referencing them -- I create all objects and the calculation is triggered on demand) I am stuck -- how to do this (limit access up to parent class, no more, no less)? I suspect I'll get answer-question first -- "but why you don't split the evaluation per each field" -- so I answer this by example: how do you calculate min and max value of a collection? In a fast way? The answer is -- in one pass. This is why I have one eval function which does calculations and sets all fields at once.

    Read the article

  • Java downcasting and is-A has-A relationship

    - by msharma
    HI, I have a down casting question, I am a bit rusty in this area. I have 2 clasess like this: class A{ int i; String j ; //Getters and setters} class B extends A{ String k; //getter and setter} I have a method like this, in a Utility helper class: public static A converts(C c){} Where C are objects that are retireved from the database and then converted. The problem is I want to call the above method by passing in a 'C' and getting back B. So I tried this: B bClasss = (B) Utility.converts(c); So even though the above method returns A I tried to downcast it to B, but I get a runtime ClassCastException. Is there really no way around this? DO I have to write a separate converts() method which returns a B class type? If I declare my class B like: class B { String k; A a;} // So instead of extending A it has-a A, getter and setters also then I can call my existing method like this: b.setA(Utility.converts(c) ); This way I can reuse the existing method, even though the extends relationship makes more sense. What should I do? Any help much appreciated. Thanks.

    Read the article

  • JavaEE: Question about design

    - by Harry Pham
    I have a JSF page that will create a new Comment. I have the managed bean of that page to be RequestScoped managed bean. @ManagedBean(name="PostComment") @RequestScoped public class PostComment { private Comment comment = null; @ManagedProperty(value="#{A}") private A a; //A is a ViewScoped Bean @ManagedProperty(value="#{B}") private B b; //B is a ViewScoped Bean @PostConstruct public void init(){ comment = new Comment(); } // setters and getters for comment and all the managed property variable public void postComment(String location){ //persist the new comment ... if(location.equals("A")){ //update the comment list on page A }else if(location.equals("B")){ //update the comment list on page B } } } As you can see from the code above, 2 ViewScoped bean A and B will both use method postComment(), and getter getComment() from bean PostComment. The problem I am having right now is that, if I am on A, constructor of A will load, but it will also load constructor of bean B. This make my page load twice as slow. What would be the best way to solve this problem?

    Read the article

  • How do I add array indices to the XML produced by JAXB?

    - by oconnor0
    I have a Java bean ala @XmlRootElement public class Bean { @XmlElementWrapper(name = "ints") @XmlElement(name = "int") int[] values; // constructors, getters, setters, etc... } JAXB is producing XML like <bean> <ints> <int>12</int> <int>34</int> <int>56</int> </ints> </bean> I would like the array indices to be included on the <int> tags as array position conveys important value. Preferably as attributes like <bean> <ints> <int id='0'>12</int> <int id='1'>34</int> <int id='2'>56</int> </ints> </bean> Is there a way to do this?

    Read the article

  • Two entities with @ManyToOne should join the same table

    - by Ivan Yatskevich
    I have the following entities Student @Entity public class Student implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; //getter and setter for id } Teacher @Entity public class Teacher implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; //getter and setter for id } Task @Entity public class Task implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne(optional = false) @JoinTable(name = "student_task", inverseJoinColumns = { @JoinColumn(name = "student_id") }) private Student author; @ManyToOne(optional = false) @JoinTable(name = "student_task", inverseJoinColumns = { @JoinColumn(name = "teacher_id") }) private Teacher curator; //getters and setters } Consider that author and curator are already stored in DB and both are in the attached state. I'm trying to persist my Task: Task task = new Task(); task.setAuthor(author); task.setCurator(curator); entityManager.persist(task); Hibernate executes the following SQL: insert into student_task (teacher_id, id) values (?, ?) which, of course, leads to null value in column "student_id" violates not-null constraint Can anyone explain this issue and possible ways to resolve it?

    Read the article

  • How to perform Rails model validation checks within model but outside of filters using ledermann-rails-settings and extensions

    - by user1277160
    Background I'm using ledermann-rails-settings (https://github.com/ledermann/rails-settings) on a Rails 2/3 project to extend virtually the model with certain attributes that don't necessarily need to be placed into the DB in a wide table and it's working out swimmingly for our needs. An additional reason I chose this Gem is because of the post How to create a form for the rails-settings plugin which ties ledermann-rails-settings more closely to the model for the purpose of clean form_for usage for administrator GUI support. It's a perfect solution for addressing form_for support although... Something that I'm running into now though is properly validating the dynamic getters/setters before being passed to the ledermann-rails-settings module. At the moment they are saved immediately, regardless if the model validation has actually fired - I can see through script/console that validation errors are being raised. Example For instance I would like to validate that the attribute :foo is within the range of 0..100 for decimal usage (or even a regex). I've found that with the previous post that I can use standard Rails validators (surprise, surprise) but I want to halt on actually saving any values until those are addressed - ensure that the user of the GUI has given 61.43 as a numerical value. The following code has been borrowed from the quoted post. class User < ActiveRecord::Base has_settings validates_inclusion_of :foo, :in => 0..100 def self.settings_attr_accessor(*args) >>SOME SORT OF UNLESS MODEL.VALID? CHECK HERE args.each do |method_name| eval " def #{method_name} self.settings.send(:#{method_name}) end def #{method_name}=(value) self.settings.send(:#{method_name}=, value) end " end >>END UNLESS end settings_attr_accessor :foo end Anyone have any thoughts here on pulling the state of the model at this point outside of having to put this into a before filter? The goal here is to be able to use the standard validations and avoid rolling custom validation checks for each new settings_attr_accessor that is added. Thanks!

    Read the article

  • Spring: Bean fails to read off values from external Properties file when using @Value annotation

    - by daydreamer
    XML Configuration <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <util:properties id="mongoProperties" location="file:///storage/local.properties" /> <bean id="mongoService" class="com.business.persist.MongoService"></bean> </beans> and MongoService looks like @Service public class MongoService { @Value("#{mongoProperties[host]}") private String host; @Value("#{mongoProperties[port]}") private int port; @Value("#{mongoProperties[database]}") private String database; private Mongo mongo; private static final Logger LOGGER = LoggerFactory.getLogger(MongoService.class); public MongoService() throws UnknownHostException { LOGGER.info("host=" + host + ", port=" + port + ", database=" + database); mongo = new Mongo(host, port); } public void putDocument(@Nonnull final DBObject document) { LOGGER.info("inserting document - " + document.toString()); mongo.getDB(database).getCollection(getCollectionName(document)).insert(document, WriteConcern.SAFE); } I write my MongoServiceTest as public class MongoServiceTest { @Autowired private MongoService mongoService; public MongoServiceTest() throws UnknownHostException { mongoRule = new MongoRule(); } @Test public void testMongoService() { final DBObject document = DBContract.getUniqueQuery("001"); document.put(DBContract.RVARIABLES, "values"); document.put(DBContract.PVARIABLES, "values"); mongoService.putDocument(document); } and I see failures in tests as 12:37:25.224 [main] INFO c.s.business.persist.MongoService - host=null, port=0, database=null java.lang.NullPointerException at com.business.persist.MongoServiceTest.testMongoService(MongoServiceTest.java:40) Which means bean was not able to read the values from local.properties local.properties ### === MongoDB interaction === ### host="127.0.0.1" port=27017 database=contract How do I fix this? update It doesn't seem to read off the values even after creating setters/getters for the fields. I am really clueless now. How can I even debug this issue? Thanks much!

    Read the article

  • Using EhCache for session.createCriteria(...).list()

    - by James Smith
    I'm benchmarking the performance gains from using a 2nd level cache in Hibernate (enabling EhCache), but it doesn't seem to improve performance. In fact, the time to perform the query slightly increases. The query is: session.createCriteria(MyEntity.class).list(); The entity is: @Entity @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class MyEntity { @Id @GeneratedValue private long id; @Column(length=5000) private String data; //---SNIP getters and setters--- } My hibernate.cfg.xml is: <!-- all the normal stuff to get it to connect & map the entities plus:--> <property name="hibernate.cache.region.factory_class"> net.sf.ehcache.hibernate.EhCacheRegionFactory </property> The MyEntity table contains about 2000 rows. The problem is that before adding in the cache, the query above to list all entities took an average of 65 ms. After the cache, they take an average of 74 ms. Is there something I'm missing? Is there something extra that needs to be done that will increase performance?

    Read the article

  • c++ Design pattern for CoW, inherited classes, and variable shared data?

    - by krunk
    I've designed a copy-on-write base class. The class holds the default set of data needed by all children in a shared data model/CoW model. The derived classes also have data that only pertains to them, but should be CoW between other instances of that derived class. I'm looking for a clean way to implement this. If I had a base class FooInterface with shared data FooDataPrivate and a derived object FooDerived. I could create a FooDerivedDataPrivate. The underlying data structure would not effect the exposed getters/setters API, so it's not about how a user interfaces with the objects. I'm just wondering if this is a typical MO for such cases or if there's a better/cleaner way? What peeks my interest, is I see the potential of inheritance between the the private data classes. E.g. FooDerivedDataPrivate : public FooDataPrivate, but I'm not seeing a way to take advantage of that polymorphism in my derived classes. class FooDataPrivate { public: Ref ref; // atomic reference counting object int a; int b; int c; }; class FooInterface { public: // constructors and such // .... // methods are implemented to be copy on write. void setA(int val); void setB(int val); void setC(int val); // copy constructors, destructors, etc. all CoW friendly private: FooDataPrivate *data; }; class FooDerived : public FooInterface { public: FooDerived() : FooInterface() {} private: // need more shared data for FooDerived // this is the ???, how is this best done cleanly? };

    Read the article

  • Two entities with @ManyToOne joins the same table

    - by Ivan Yatskevich
    I have the following entities Student @Entity public class Student implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; //getter and setter for id } Teacher @Entity public class Teacher implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; //getter and setter for id } Task @Entity public class Task implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne(optional = false) @JoinTable(name = "student_task", inverseJoinColumns = { @JoinColumn(name = "student_id") }) private Student author; @ManyToOne(optional = false) @JoinTable(name = "student_task", inverseJoinColumns = { @JoinColumn(name = "teacher_id") }) private Teacher curator; //getters and setters } Consider that author and curator are already stored in DB and both are in the attached state. I'm trying to persist my Task: Task task = new Task(); task.setAuthor(author); task.setCurator(curator); entityManager.persist(task); Hibernate executes the following SQL: insert into student_task (teacher_id, id) values (?, ?) which, of course, leads to null value in column "student_id" violates not-null constraint Can anyone explain this issue and possible ways to resolve it?

    Read the article

  • How do you pass a generic delegate argument to a method in .NET 2.0 - UPDATED

    - by Seth Spearman
    Hello, I have a class with a delegate declaration as follows... Public Class MyClass Public Delegate Function Getter(Of TResult)() As TResult ''#the following code works. Public Shared Sub MyMethod(ByVal g As Getter(Of Boolean)) ''#do stuff End Sub End Class However, I do not want to explicitly type the Getter delegate in the Method call. Why can I not declare the parameter as follows... ... (ByVal g As Getter(Of TResult)) Is there a way to do it? My end goal was to be able to set a delegate for property setters and getters in the called class. But my reading indicates you can't do that. So I put setter and getter methods in that class and then I want the calling class to set the delegate argument and then invoke. Is there a best practice for doing this. I realize in the above example that I can set set the delegate variable from the calling class...but I am trying to create a singleton with tight encapsulation. For the record, I can't use any of the new delegate types declared in .net35. Answers in C# are welcome. Any thoughts? Seth

    Read the article

  • Google App Engine datastore encoding?

    - by sernaferna
    I'm using the GAE datastore for a Java application, and storing some text that will be in numerous languages. In my servlet, I'm first checking to see if there's any data in the data store, and, if not, I'm creating some, similar to the following: ArrayList<Lang> list = new ArrayList<Lang>(); list.add(new Lang("EN", "English", 1)); list.add(new Lang("ES", "Español", 0)); //more languages here... PersistenceManager pm = PMF.get().getPersistenceManager(); for(Lang l : list) { pm.makePersistent(l); } Since this is using JDO, I guess I should include the relevent parts of the Lang class too: @PersistenceCapable public class Lang { @PrimaryKey private String code; @Persistent private String name; @Persistent private int popularity; // getters & setters & constructors... } However, the non-ASCII characters are giving me grief. I've set my Eclipse project to use the UTF-8 encoding instead of the default Cp1252, so I think I'm okay from that perspective, but when I use the App Engine Data Viewer to look at my data, that Español entry becomes Español, and when I click on it to view it, I get a 500 Server Error. (There are some other entries with right-to-left text that don't even show up in the Data Viewer at all, but one problem at a time...) Is there anything special I can do in my code to set the character encoding, or specify to GAE that the data I'm storing is UTF-8? Or is the problem on the Eclipse side, and is there something I should be doing with my Java code?

    Read the article

  • Java HashMap containsKey always false

    - by Dennis
    I have the funny situation, that I store a Coordinate into a HashMap<Coordinate, GUIGameField>. Now, the strange thing about it is, that I have a fragment of code, which should guard, that no coordinate should be used twice. But if I debug this code: if (mapForLevel.containsKey(coord)) { throw new IllegalStateException("This coordinate is already used!"); } else { ...do stuff... } ... the containsKey always returns false, although I stored a coordinate with a hashcode of 9731 into the map and the current coord also has the hashcode 9731. After that, the mapForLevel.entrySet() looks like: (java.util.HashMap$EntrySet) [(270,90)=gui.GUIGameField@29e357, (270,90)=gui.GUIGameField@ca470] What could I have possibly done wrong? I ran out of ideas. Thanks for any help! public class Coordinate { int xCoord; int yCoord; public Coordinate(int x, int y) { ...store params in attributes... } ...getters & setters... @Override public int hashCode() { int hash = 1; hash = hash * 41 + this.xCoord; hash = hash * 31 + this.yCoord; return hash; } }

    Read the article

  • NSOutlineView not redrawing

    - by Septih
    Hello, I have an NSOutlineView with checkboxes. I have the checkbox state bound to a node item with the key shouldBeCopied. In the node item I have the getters and setters like so: -(BOOL)shouldBeCopied { if([[self parent] shouldBeCopied]) return YES; return shouldBeCopied; } -(void)setShouldBeCopied:(BOOL)value { shouldBeCopied = value; if(value && [[self children] count] > 0) [[self delegate] reloadData]; } The idea here is that if the parent is checked, so should the children. The problem I'm having is that when I check the parent, it does not update that view of the children if they are already expanded. I can understand that it should not be updated by the bindings because i'm not actually changing the value. But should reloadData not cause the bindings to re-get the value, thus calling -shouldBeCopied for the children? I have tried a few other things such as -setNeedsDisplay and -reloadItem:nil reloadChildren:YES but none work. I've noticed that the display gets refreshed when I swap to xcode and then back again and that's all I want, so how do I get it to behave that way?

    Read the article

  • Spring 3 MVC validation BindingResult doesn't contain any errors

    - by Travelsized
    I'm attempting to get a Spring 3.0.2 WebMVC project running with the new annotated validation support. I have a Hibernate entity annotated like this: @Entity @Table(name = "client") public class Client implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "clientId", nullable = false) @NotEmpty private Integer clientId; @Basic(optional = false) @Column(name = "firstname", nullable = false, length = 45) @NotEmpty @Size(min=2, max=45) private String firstname; ... more fields, getters and setters } I've turned on mvc annotation support in my applicationContext.xml file: <mvc:annotation-driven /> And I have a method in my controller that responds to a form submission: @RequestMapping(value="/addClient.htm") public String addClient(@ModelAttribute("client") @Valid Client client, BindingResult result) { if(result.hasErrors()) { return "addClient"; } service.storeClient(client); return "clientResult"; } When my app loads in the server, I can see in the server log file that it loads a validator: 15 [http-8084-2] INFO org.hibernate.validator.util.Version - Hibernate Validator 4.0.2.GA The problem I'm having is that the validator doesn't seem to kick in. I turned on the debugger, and when I get into the controller method, the BindingResult contains 0 errors after I submit an empty form. (The BindingResult does show that it contains the Client object as a target.) It then proceeds to insert a record without an Id and throws an exception. If I fill out an Id but leave the name blank, it creates a record with the Id and empty fields. What steps am I missing to get the validation working?

    Read the article

  • C++ Initialize array in constructor EXC_BAD_ACCESS

    - by user890395
    I'm creating a simple constructor and initializing an array: // Construtor Cinema::Cinema(){ // Initalize reservations for(int i = 0; i < 18; i++){ for(int j = 0; j < 12; j++){ setReservation(i, j, 0); } } // Set default name setMovieName("N/A"); // Set default price setPrice(8); } The setReservation function: void Cinema::setReservation(int row, int column, int reservation){ this->reservations[row][column] = reservation; } The setMovieName function: void Cinema::setMovieName(std::string movieName){ this->movieName = movieName; } For some odd reason when I run the program, the setMovieName function gives the following error: "Program Received Signal: EXC_BAD_ACCESS" If I take out the for-loop that initializes the array of reservations, the problem goes away and the movie name is set without any problems. Any idea what I'm doing wrong? This is the Cinema.h file: #ifndef Cinema_h #define Cinema_h class Cinema{ private: int reservations[17][11]; std::string movieName; float price; public: // Construtor Cinema(); // getters/setters int getReservation(int row, int column); int getNumReservations(); std::string getMovieName(); float getPrice(); void setReservation(int row, int column, int reservation); void setMovieName(std::string movieName); void setPrice(float price); }; #endif

    Read the article

  • How do I alias the scala setter method 'myvar_$(myval)' to something more pleasing when in java?

    - by feydr
    I've been converting some code from java to scala lately trying to tech myself the language. Suppose we have this scala class: class Person() { var name:String = "joebob" } Now I want to access it from java so I can't use dot-notation like I would if I was in scala. So I can get my var's contents by issuing: person = Person.new(); System.out.println(person.name()); and set it via: person = Person.new(); person.name_$eq("sallysue"); System.out.println(person.name()); This holds true cause our Person Class looks like this in javap: Compiled from "Person.scala" public class Person extends java.lang.Object implements scala.ScalaObject{ public Person(); public void name_$eq(java.lang.String); public java.lang.String name(); public int $tag() throws java.rmi.RemoteException; } Yes, I could write my own getters/setters but I hate filling classes up with that and it doesn't make a ton of sense considering I already have them -- I just want to alias the _$eq method better. (This actually gets worse when you are dealing with stuff like antlr because then you have to escape it and it ends up looking like person.name_\$eq("newname"); Note: I'd much rather have to put up with this rather than fill my classes with more setter methods. So what would you do in this situation?

    Read the article

  • Protecting sensitive entity data

    - by Andreas
    Hi, I'm looking for some advice on architecture for a client/server solution with some peculiarities. The client is a fairly thick one, leaving the server mostly to peristence, concurrency and infrastructure concerns. The server contains a number of entities which contain both sensitive and public information. Think for example that the entities are persons, assume that social security number and name are sensitive and age is publicly viewable. When starting the client, the user is presented with a number of entities, not disclosing any sensitive information. At any time the user can choose to log in and authenticate against the server, given the authentication is successful the user is granted access to the sensitive information. The client is hosting a domain model and I was thinking of implementing this as some kind of "lazy loading", making the first request instantiating the entities and later refreshing them with sensitive data. The entity getters would throw exceptions on sensitive information when they've not been disclosed, f.e.: class PersonImpl : PersonEntity { private bool undisclosed; public override string SocialSecurityNumber { get { if (undisclosed) throw new UndisclosedDataException(); return base.SocialSecurityNumber; } } } Another more friendly approach could be to have a value object indicating that the value is undisclosed. get { if (undisclosed) return undisclosedValue; return base.SocialSecurityNumber; } Some concerns: What if the user logs in and then out, the sensitive data has been loaded but must be disclosed once again. One could argue that this type of functionality belongs within the domain and not some infrastructural implementation(i.e. repository implementations). As always when dealing with a larger number of properties there's a risk that this type of functionality clutters the code Any insights or discussion is appreciated!

    Read the article

  • Use of properties vs backing-field inside owner class

    - by whatispunk
    I love auto-implemented properties in C# but lately there's been this elephant standing in my cubicle and I don't know what to do with him. If I use auto-implemented properties (hereafter "aip") then I no longer have a private backing field to use internally. This is fine because the aip has no side-effects. But what if later on I need to add some extra processing in the get or set? Now I need to create a backing-field so I can expand my getters and setters. This is fine for external code using the class, because they won't notice the difference. But now all of the internal references to the aip are going to invoke these side-effects when they access the property. Now all internal access to the once aip must be refactored to use the backing-field. So my question is, what do most of you do? Do you use auto-implemented properties or do you prefer to always use a backing-field? What do you think about properties with side-effects?

    Read the article

  • How do I alias the scala setter method 'myvar_$eq(myval)' to something more pleasing when in java?

    - by feydr
    I've been converting some code from java to scala lately trying to teach myself the language. Suppose we have this scala class: class Person() { var name:String = "joebob" } Now I want to access it from java so I can't use dot-notation like I would if I was in scala. So I can get my var's contents by issuing: person = Person.new(); System.out.println(person.name()); and set it via: person = Person.new(); person.name_$eq("sallysue"); System.out.println(person.name()); This holds true cause our Person Class looks like this in javap: Compiled from "Person.scala" public class Person extends java.lang.Object implements scala.ScalaObject{ public Person(); public void name_$eq(java.lang.String); public java.lang.String name(); public int $tag() throws java.rmi.RemoteException; } Yes, I could write my own getters/setters but I hate filling classes up with that and it doesn't make a ton of sense considering I already have them -- I just want to alias the _$eq method better. (This actually gets worse when you are dealing with stuff like antlr because then you have to escape it and it ends up looking like person.name_\$eq("newname"); Note: I'd much rather have to put up with this rather than fill my classes with more setter methods. So what would you do in this situation?

    Read the article

  • Glassfish complaining about JSF component IDs

    - by Brian
    Hello All I am very new to JSF (v2.0) and I am attempting to learn it at places like netbeans.org and coreservlets.com. I am working on a very simple "add/subtract/multiply/divide" Java webapp and I have run into a problem. When I first started out, the application was enter two numbers and hit a '+' key and they would be automatically added together. Now that I have added more complexity I am having trouble getting the operation to the managed bean. This is what I had when it was just "add": <h:inputText styleClass="display" id="number01" size="4" maxlength="3" value="#{Calculator.number01}" /> <h:inputText styleClass="display" id="number02" size="4" maxlength="3" value="#{Calculator.number02}" /> <h:commandButton id="add" action="answer" value="+" /> For the "answer" page, I display the answer like this: <h:outputText value="#{Calculator.answer}" /> I had the proper getters and setters in the Calculator.java managed bean and the operation worked perfectly. Now I have added the other three operations and I am having trouble visualizing how to get the operation parameter to the bean so that I can switch around it. I tried this: <h:commandButton id="operation" action="answer" value="+" /> <h:commandButton id="operation" action="answer" value="-" /> <h:commandButton id="operation" action="answer" value="*" /> <h:commandButton id="operation" action="answer" value="/" /> However, Glassfish complained that I have already used "operation" once and I am trying to use it four times here. Any adivce/tips on how to get multiple operations to the managed bean so that it can preform the desired operation? Thank you for taking the time to read.

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15  | Next Page >