Search Results

Search found 4593 results on 184 pages for 'constructor injection'.

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

  • 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

  • Accessing constructor from abstract base class with reflection

    - by craesh
    Hi! I'm playing around with Java's Reflection. I have an abstract class Base with a constructor. abstract class Base { public Base( String foo ) { // do some magic } } I have some further classes extending Base. They don't contain much logic. I want to instantiate them with Base's constructor, without having to write some proxy contructors in those derived classes. And of course, I want to instantiate those derived classes with Reflection. Say: Class cls = SomeDerivedClass.class; Constructor constr; constr = cls.getConstructor( new Class[] { String.class } ); // will return null Class clsBase = Base.class; constr = clsBase.getConstructor( new Class[] { String.class } ); // ok Base obj = (Base) constr.newInstance( new Object[] { "foo" } ); // will throw InstantiationException because it belongs to an abstract class Any ideas, how I can instantiate a derived class with Base's constructor? Or must I declare those dumb proxy constructors?

    Read the article

  • Can a single argument constructor with a default value be subject to implicit type conversion

    - by Richard
    I understand the use of the explicit keyword to avoid the implicit type conversions that can occur with a single argument constructor, or with a constructor that has multiple arguments of which only the first does not have a default value. However, I was wondering, does a single argument constructor with a default value behave the same as one without a default value when it comes to implicit conversions?

    Read the article

  • Good style for handling constructor failure of critical object

    - by mtlphil
    I'm trying to decide between two ways of instantiating an object & handling any constructor exceptions for an object that is critical to my program, i.e. if construction fails the program can't continue. I have a class SimpleMIDIOut that wraps basic Win32 MIDI functions. It will open a MIDI device in the constructor and close it in the destructor. It will throw an exception inherited from std::exception in the constructor if the MIDI device cannot be opened. Which of the following ways of catching constructor exceptions for this object would be more in line with C++ best practices Method 1 - Stack allocated object, only in scope inside try block #include <iostream> #include "simplemidiout.h" int main() { try { SimpleMIDIOut myOut; //constructor will throw if MIDI device cannot be opened myOut.PlayNote(60,100); //..... //myOut goes out of scope outside this block //so basically the whole program has to be inside //this block. //On the plus side, it's on the stack so //destructor that handles object cleanup //is called automatically, more inline with RAII idiom? } catch(const std::exception& e) { std::cout << e.what() << std::endl; std::cin.ignore(); return 1; } std::cin.ignore(); return 0; } Method 2 - Pointer to object, heap allocated, nicer structured code? #include <iostream> #include "simplemidiout.h" int main() { SimpleMIDIOut *myOut; try { myOut = new SimpleMIDIOut(); } catch(const std::exception& e) { std::cout << e.what() << std::endl; delete myOut; return 1; } myOut->PlayNote(60,100); std::cin.ignore(); delete myOut; return 0; } I like the look of the code in Method 2 better, don't have to jam my whole program into a try block, but Method 1 creates the object on the stack so C++ manages the object's life time, which is more in tune with RAII philosophy isn't it? I'm still a novice at this so any feedback on the above is much appreciated. If there's an even better way to check for/handle constructor failure in a siatuation like this please let me know.

    Read the article

  • Getting the instance when Constructor#newInstance throws?

    - by Shtééf
    I'm working on a simple plugin system, where third party plugins implement a Plugin interface. A directory of JARs is scanned, and the implementing classes are instantiated with Constructor#newInstance. The thing is, these plugins call back into register* methods of the plugin host. These registrations use the Plugin instance as a handle. My problem is how to clean up these registrations if the constructor decides to fail and throw halfway through. InvocationTargetException doesn't seem to have anything on it to get the instance. Is there a way to get at the instance of an exception throwing constructor? P.S.: It's typically strongly advised to users that the constructor not do anything, but in practice people are doing it any ways.

    Read the article

  • Issue calling superclass method in subclass constructor

    - by stormin986
    I get a NullPointerException calling a Superclass Method in Subclass Inner Class Constructor... What's the Deal? In my application's main class (subclass of Application), I have a public inner class that simply contains 3 public string objects. In the parent class I declare an object of that inner class. public class MainApplication extends Application { public class Data { public String x; public String y; public String z; } private Data data; MainApplication() { data = new Data() data.x = SuperClassMethod(); } } After I instantiate the object in the constructor, I get a runtime error when I try to assign a value in the inner class with a superclass method. Any idea what's up here?? Can you not call superclass methods in the subclass constructor? ** Edit ** Original question was about inner class member assignment in outer class constructor. Turned out the issue was with calling a superclass method in the class's constructor. It was giving me a null pointer exception. Thus, the question has changed.

    Read the article

  • C++ superclass constructor calling rules

    - by levik
    What are the C++ rules for calling the superclass constructor from a subclass one?? For example I know in Java, you must do it as the first line of the subclass constructor (and if you don't an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).

    Read the article

  • In Java, is it possible for a super constructor invocation actually invoke a constructor in the calling class?

    - by John Assymptoth
    Super constructor invocation definition: [Primary.] [NonWildTypeArguments] super ( ArgumentListopt ) ; A super constructor call can be prefixed by an Primary expression. Example (taken from JLS): class Outer { class Inner{ } } class ChildOfInner extends Outer.Inner { ChildOfInner() { (new Outer()).super(); // (new Outer()) is the Primary } } Does a Primary expression exist that makes the call to super() the invocation of a constructor of the calling class? Or Java prevents that?

    Read the article

  • MVVM application architecture, where to put dependency injection configuration class, BusinessLayer and Common interfaces?

    - by gt.guybrush
    Planning my architecture for an MVVM application I come to this: MyApp.UI View MyApp.BusinessLayer ViewModel MyApp.DataAccessLayer RepositoryImplEF MyApp.DomainLayer DomainObject RepositoryInterface MyApp.Common Logging Security Utility (contains some reflection method used by many levels) CustomException MyApp.UnitTest I was inspired by Domain-driven-desing, test-driven-development and onion architecture but not sure to have done all well. I am not sure of a couple of things: where to put dependency injection configuration class? In the common project? where to put BusinessLayer interfaces? in Domain layer? where to put Common interfaces? in Domain layer? But Common in referenced from domain (for some reflection utilities and for DI if the response to 1. is yes) and circular reference isn't good

    Read the article

  • why Cannot invoke super constructor from enum constructor ?

    - by hilal
    public enum A { A(1); private A(int i){ } private A(){ super(); // compile - error // Cannot invoke super constructor from enum constructor A() } } and here is the hierarchy of enum A extends from abstract java.lang.Enum extends java.lang.Object Class c = Class.forName("/*path*/.A"); System.out.println(c.getSuperclass().getName()); System.out.println(Modifier.toString(c.getSuperclass().getModifiers()).contains("abstract")); System.out.println(c.getSuperclass().getSuperclass().getName());

    Read the article

  • Dependency Injection Constructor Madness

    - by JP
    I find that my constructors are starting to look like this: public MyClass(Container con, SomeClass1 obj1, SomeClass2, obj2.... ) with ever increasing parameter list. Since "Container" is my dependency injection container, why can't I just do this: public MyClass(Container con) for every class? What are the downsides? If I do this, it feels like I'm using a glorified static. Please share your thoughts on IoC and Dependency Injection madness. Thanks in advance. -JP

    Read the article

  • Dependency Injection book recommendation(s)

    - by Portman
    It seems like there are very few books (yes, I read books) on Dependency Injection. The Amazon tag for "dependency injection" lists only a few titles, and all of them are specifically about Spring for Java. Are there any books out there that cover DI/IoC in general? Or any that include a survey of multiple DI frameworks? Or any that cover .NET in lieu of or in addition to Java? Or do we have to rely on this newfangled interweb instead of dead trees...

    Read the article

  • How to use Dependency Injection with ASP.NET

    - by Schneider
    I am trying to work out a way to use Dependency Injection with ASP.NET controls. I have got lots of controls that create repositories directly, and use those to access and bind to data etc. I am looking for a pattern where I can pass repositories to the controls externally (IoC), so my controls remain unaware of how repositories are constructed and where they come from etc. I would prefer not to have a dependency on the IoC container from my controls, therefore I just want to be able to construct the controls with constructor or property injection. (And just to complicate things, these controls are being constructed and placed on the page by a CMS at runtime!) Any thoughts?

    Read the article

  • Spring constructor injection of SLF4J logger - how to get injection target class?

    - by disown
    I'm trying to use Spring to inject a SLF4J logger into a class like so: @Component public class Example { private final Logger logger; @Autowired public Example(final Logger logger) { this.logger = logger; } } I've found the FactoryBean class, which I've implemented. But the problem is that I cannot get any information about the injection target: public class LoggingFactoryBean implements FactoryBean<Logger> { @Override public Class<?> getObjectType() { return Logger.class; } @Override public boolean isSingleton() { return false; } @Override public Logger getObject() throws Exception { return LoggerFactory.getLogger(/* how do I get a hold of the target class (Example.class) here? */); } } Is FactoryBean even the right way to go? When using picocontainers factory injection, you get the Type of the target passed in. In guice it is a bit trickier. But how do you accomplish this in Spring?

    Read the article

  • Is dependency injection possible for JSP beans?

    - by kazanaki
    This may be a long shot question.. I am working on an application that is based on JSP/Javascript only (without a Web framework!) Is there a way to have depencency injection for JSP beans? By jsp beans I mean beans defined like this <jsp:useBean id="cart" scope="session" class="session.Carts" /> Is there a way/library/hack to intercept the bean creation so that when "cart" is referenced for the first time, some some of injection takes place? Can I define somewhere a "listener" for JSP beans (like you can do for JSF beans for example)? I am free to do anything I want in the back-end, but I cannot add a web framework in the front-end (Don't ask!)

    Read the article

  • Constructor versus setter injection

    - by Chris
    Hi, I'm currently designing an API where I wish to allow configuration via a variety of methods. One method is via an XML configuration schema and another method is through an API that I wish to play nicely with Spring. My XML schema parsing code was previously hidden and therefore the only concern was for it to work but now I wish to build a public API and I'm quite concerned about best-practice. It seems that many favor javabean type PoJo's with default zero parameter constructors and then setter injection. The problem I am trying to tackle is that some setter methods implementations are dependent on other setter methods being called before them in sequence. I could write anal setters that will tolerate themselves being called in many orders but that will not solve the problem of a user forgetting to set the appropriate setter and therefore the bean being in an incomplete state. The only solution I can think of is to forget about the objects being 'beans' and enforce the required parameters via constructor injection. An example of this is in the default setting of the id of a component based on the id of the parent components. My Interface public interface IMyIdentityInterface { public String getId(); /* A null value should create a unique meaningful default */ public void setId(String id); public IMyIdentityInterface getParent(); public void setParent(IMyIdentityInterface parent); } Base Implementation of interface: public abstract class MyIdentityBaseClass implements IMyIdentityInterface { private String _id; private IMyIdentityInterface _parent; public MyIdentityBaseClass () {} @Override public String getId() { return _id; } /** * If the id is null, then use the id of the parent component * appended with a lower-cased simple name of the current impl * class along with a counter suffix to enforce uniqueness */ @Override public void setId(String id) { if (id == null) { IMyIdentityInterface parent = getParent(); if (parent == null) { // this may be the top level component or it may be that // the user called setId() before setParent(..) } else { _id = Helpers.makeIdFromParent(parent,getClass()); } } else { _id = id; } } @Override public IMyIdentityInterface getParent() { return _parent; } @Override public void setParent(IMyIdentityInterface parent) { _parent = parent; } } Every component in the framework will have a parent except for the top level component. Using the setter type of injection, then the setters will have different behavior based on the order of the calling of the setters. In this case, would you agree, that a constructor taking a reference to the parent is better and dropping the parent setter method from the interface entirely? Is it considered bad practice if I wish to be able to configure these components using an IoC container? Chris

    Read the article

  • How to model dependency injection in UML ?

    - by hjo1620
    I have a Contract class. The contract is valid 1 Jan 2010 - 31 Dec 2010. It can be in state Active or Passive, depending on which date I ask the instance for it's state. ex. if I ask 4 July 2010, it's in state Active, but if I ask 1 Jan 2011, it's in state Passive. Instances are created using constructor dependency injection, i.e. they are either Active or Passive already when created, null is not allowed as a parameter for the internal state member. One initial/created vertex is drawn in UML. I have two arrows, leading out from the initial vertex, one leading to state Active and the other to state Passive. Is this a correct representation of dependency injection in UML ? This is related to http://stackoverflow.com/questions/2779922/how-model-statemachine-when-state-is-dependent-on-a-function which initiated the question on how to model DI in general, in UML.

    Read the article

  • Dependency Injection & Singleton Design pattern

    - by SysAdmin
    How do we identify when to use dependency injection or singleton pattern. I have read in lot of websites where they say "Use Dependency injection over singleton pattern". But I am not sure if I totally agree with them. For my small or medium scale projects I definitely see the use of singleton pattern straightforward. For example Logger. I could use Logger.GetInstance().Log(...) But, instead of this, why do I need to inject every class I create, with the logger's instance?.

    Read the article

  • How exactly does dependency injection reduce coupling?

    - by dotnetdev
    Hi, I've done plenty of reading on Dependency Injection, but I have no idea, how does it actually reduce coupling? The analogy I have of DI is that all components are registered with a container, so theyre are like in a treasure chest. To get a component, you obviously register it first, but then you would have to interrogate the treasure chest (which is like a layer of indirection). Is this the right analogy? It doesn't make obvious how the "injection" happens, though (how would that fit in with this analogy?). Thanks

    Read the article

  • PHP Security checklist (injection, sessions etc)

    - by NoviceCoding
    So what kind of things should a person using PHP and MySql be focused on to maximize security. Things I have done: -mysql_real_escape_string all inputs -validate all inputs after escaping em -Placed random alpha numerics before my table names -50character salt + Ripemd passwords Heres where I think I am slacking: -I know know nothing about sessions and securing them. How unsafe/safe is it if all you are doing is: session_start(); $_SESSION['login']= $login; and checking it with: session_start(); if(isset($_SESSION['login'])){ -I heard something about other forms of injection like cross site injection and what not... -And probably many other things I dont know about. Is there a "checklist"/Quicktut on making php secure? I dont even know what I should be worried about.I kinda regret now not building off cakephp since I am not a pro.

    Read the article

  • SQL Injection - some sense at last!

    - by TATWORTH
    I see various articles that proclaim means to guard against SQL injection. As individual steps they are of use but since they were often proclaimed as "the solution" they were potentially misleading. At http://www.simple-talk.com/sql/learn-sql-server/sql-injection-defense-in-depth/ there is an article entitled "SQL Injection: Defense in Depth" - this article argues what I have argued myself. Remember that however low-grade the information on your web site is, if your site is hacked, the public may percive the hacking as your most sensitive information was exposed.

    Read the article

  • SQL Injection Attacks are still occurring

    - by TATWORTH
    It should be of concern to all developers that SQL Injection attacks are still occurring. Here are some resources on the subject: http://www.darkreading.com/DatabaseSecurity/util/4576/download.html (needs free registration) http://en.wikipedia.org/wiki/SQL_injection http://www.unixwiz.net/techtips/sql-injection.html http://msdn.microsoft.com/en-us/library/ms161953.aspx http://www.sitepoint.com/sql-injection-attacks-safe/ And for a funny view on it see http://xkcd.com/327/ So what are you doing to harden your applications?

    Read the article

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