In the following code userexception class defined below is inheriting ApplicationException class. To my knowledge I know base keyword is used to pass the parameter, to parent class constructor. Here ApplicationException is the parent class. If this is the case, I wonder how does the object e of userexception class in the catch block can act as an argument and store the information "Transaction was unuccessful" , though Amount_To_WithDraw is not the parent class for userexception class. I want to know the in and out mechanism happening here when an exception is caught.
class Program
{
static void Main(string[] args)
{
Amount_To_WithDraw A = new Amount_To_WithDraw();
Console.WriteLine("Enter the amount to withdraw");
int cash = Convert.ToInt32(Console.ReadLine());
A.CheckBalance(cash);
Console.Read();
}
}
class userexception : ApplicationException
{
public userexception(string Message)
: base("Transaction was unsuccessful") -> for which class base
refers to here.
{
Console.WriteLine(Message);
}
}
class Amount_To_WithDraw
{
public void CheckBalance(int Amount)
{
int Balance = 1000;
try
{
if ((Balance - Amount) < 500 && (Balance - Amount) > 0)
{
throw new userexception("Least Balance");
}
else if ((Balance - Amount) < 0)
{
throw new userexception("Transaction Leads To Negative Balance");
}
else
Console.WriteLine("Transaction Success");
}
catch (userexception e) -> how can the object e of userexception class
can be considered as an argument for the
parameter sent using base key word
above.
{
Console.WriteLine(e.Message);
}
}
}
Ignore exceptions here. All you're seeing is the equivalent of this:
public class Parent
{
private readonly string message;
public string Message { get { return message; } }
public Parent(string message)
{
this.message = message;
}
}
public class Child : Parent
{
// Just pass the message parameter up to the parent
public Child(string message) : base(message) {}
}
Parent x = new Child("foo");
Console.WriteLine(x.Message);
It's exactly the same. In your case, you're using the Exception.Message property, which is populated by the message passed up the constructor chain.
It's unfortunate that you've called the parameter Message in the userexception constructor - partly because it's unconventional (it should start with m; your type name ignores naming conventions too), partly because you're not passing it up as the exception message, and partly because it has the same name as the property that you're later fetching.
You might find the whole thing more understandable if you change that constructor to:
public userexception(string message)
: base("Transaction was unsuccessful: " + message)
{
}
Then you'd end up with your caught exception having a Message property value of:
Transaction was unsuccessful: Least Balance
(or whatever).
Related
I have taken the MixedType example code that comes with the java stream client (https://github.com/GetStream/stream-java) and added a update step using updateActivities. After the update the activity stored in stream loses the 'type' attribute. Jackson uses this attribute when you get the activities again and it is deserialising them.
So I get:
Exception in thread "main" Disconnected from the target VM, address: '127.0.0.1:60016', transport: 'socket'
com.fasterxml.jackson.databind.JsonMappingException: Could not resolve type id 'null' into a subtype of [simple type, class io.getstream.client.apache.example.mixtype.MixedType$Match]
at [Source: org.apache.http.client.entity.LazyDecompressingInputStream#29ad44e3; line: 1, column: 619] (through reference chain: io.getstream.client.model.beans.StreamResponse["results"]->java.util.ArrayList[1])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.unknownTypeException(DeserializationContext.java:849)
See here where I have updated the example:
https://github.com/puntaa/stream-java/blob/master/stream-repo-apache/src/test/java/io/getstream/client/apache/example/mixtype/MixedType.java
Any idea what is going on here?
The issue here is originated by Jackson which cannot get the actual instance type of an object inside the collection due to the Java type erasure, if you want to know more about it please read this issue: https://github.com/FasterXML/jackson-databind/issues/336 (which also provides some possible workarounds).
The easiest way to solve it, would be to manually force the value of the property type from within the subclass as shown in the example below:
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
#JsonSubTypes({
#JsonSubTypes.Type(value = VolleyballMatch.class, name = "volley"),
#JsonSubTypes.Type(value = FootballMatch.class, name = "football")
})
static abstract class Match extends BaseActivity {
private String type;
public String getType() {
return type;
}
}
static class VolleyballMatch extends Match {
private int nrOfServed;
private int nrOfBlocked;
public VolleyballMatch() {
super.type = "volley";
}
public int getNrOfServed() {
return nrOfServed;
}
public void setNrOfServed(int nrOfServed) {
this.nrOfServed = nrOfServed;
}
public void setNrOfBlocked(int nrOfBlocked) {
this.nrOfBlocked = nrOfBlocked;
}
public int getNrOfBlocked() {
return nrOfBlocked;
}
}
static class FootballMatch extends Match {
private int nrOfPenalty;
private int nrOfScore;
public FootballMatch() {
super.type = "football";
}
public int getNrOfPenalty() {
return nrOfPenalty;
}
public void setNrOfPenalty(int nrOfPenalty) {
this.nrOfPenalty = nrOfPenalty;
}
public int getNrOfScore() {
return nrOfScore;
}
public void setNrOfScore(int nrOfScore) {
this.nrOfScore = nrOfScore;
}
}
I was successfully using classLoader.getResourceAsStream until I turned my class into a singleton. Now I'm getting a null pointer exception, but I don't know exactly why changing my class to a singleton would cause the classLoader.getResourceAsStream to throw a null pointer exception.
class ZipCodeCache {
static pathAndFileName = 'com/generator/data/ZipCode.txt'
static inputStream = this.class.classLoader.getResourceAsStream(pathAndFileName)
private static volatile instance
private ZipCodeCache() {}
static ZipCodeCache getInstance(){
if (instance) {
return instance
} else {
synchronized(ZipCodeCache) {
if (instance) {
instance
} else {
instance = new ZipCodeCache()
loadMaps()
}
}
}
return instance
}
There's no such thing as this when you try to get the resource
Try
static inputStream = ZipCodeCache.classLoader.getResourceAsStream(pathAndFileName)
As #ataylor put it, this returns the class, ZipCodeCache. this.class returns java.lang.Class, and this.class.classLoader returns null
Use this.classLoader, or, i would prefer this, because it is more readable: ZipCodeCache.classLoader
Since you are using a singleton, using 'this' to access the class.classLoader.getResourceAsStream will return null. You must first instantiate the instance and then use the instance to access the class.classLoader. In the code snipping below, Move class.classLoader.getResourceAsStream, down into the loadMaps() method and changed 'this' to 'instance'.
class ZipCodeCache {
static pathAndFileName = 'com/generator/data/ZipCode.txt'
private static volatile instance
private ZipCodeCache() {}
static ZipCodeCache getInstance(){
if (instance) {
return instance
} else {
synchronized(ZipCodeCache) {
if (instance) {
instance
} else {
instance = new ZipCodeCache()
loadMaps()
}
}
}
return instance
}
private static loadMaps() {
def inputStream = instance.class.classLoader.getResourceAsStream(pathAndFileName)
...
}
I have a class that I've defined, and I have a number of child classes derived from it. The parent class has an enum (let's call it 'Barf'). Each descendant ALSO has an enum with the same name but not the same values. What I'm trying to figure out how to do is write a method in the ancestor class that gets the version of Barf for the actual class of the instantiated object. So if I create an instance of Ancestor, I'd like to have this method process the entries for Ancestor.Barf . If I create an instance of one of the child classes of Ancestor, I'd like to have the method process Childx.Barf values.
Obviously this is going to be a Reflection solution, but my reflection skills are pretty sparse. Any help?
Just for the fun of it, here is a possible approach:
public class Ancestor {
public enum Caffeine {
Tea,
Coffee
}
public void ProcessValues() {
var type = GetType();
var nestedEnums = from t in type.GetNestedTypes()
where t.IsEnum
select t;
var nestedEnum = nestedEnums.Single();
foreach(var val in Enum.GetValues(nestedEnum)) {
Console.WriteLine("Drinking {0}", val);
}
}
}
public class Descendant : Ancestor {
public new enum Caffeine {
Jolt,
RedBull
}
}
// The following prints:
// Drinking Jolt
// Drinking RedBull
Ancestor x = new Descendant();
x.ProcessValues();
Of course, you could achieve the same thing using polymorphism:
public class Ancestor {
public enum Caffeine {
Tea,
Coffee
}
protected virtual Type GetNestedEnum() {
return typeof(Ancestor.Caffeine);
}
public void ProcessValues() {
var nestedEnum = GetNestedEnum();
foreach(var val in Enum.GetValues(nestedEnum)) {
Console.WriteLine("Drinking {0}", val);
}
}
}
public class Descendant : Ancestor {
public new enum Caffeine {
Jolt,
RedBull
}
protected override Type GetNestedEnum() {
return typeof(Descendant.Caffeine);
}
}
As Justin Morgan has pointed out however, having the need for such a construct may be an indication of an underlying design issue in your code.
I have a problem with calling an overriden method from java class.
I have the following Java class:
public class Base
{
int state = 0;
public void called()
{
System.out.println("Hello, from called method: " + state);
}
public String getFirst()
{
return "From Base;
}
//
...
//
}
I use a groovy script to override getFirst() that so that it calls called()
def base = [ getFirst : {
called() // this line has an error
"From Second"
}] as Base
base.getFirst()
How do I implement the this?
You can't use the proxy magic in that way... At the time of the Maps declaration, it doesn't know it's going to be a Proxy for Base, so it will throw the error
Why not just do it the normal way?
def base = new Base() {
public String getFirst() {
called()
"from me"
}
}
I'd like to create a simple wrapper, which would allow calling objects methods as a fluent interface. I've been thinking about rewriting methods of a class upon creation, but this doesn't seem to work. Is this possible in some way with groovy metaprograming?
I have this kind of code snippet so far:
class FluentWrapper {
def delegate
FluentWrapper(wrapped) {
delegate = wrapped
delegate.class.getMethods().each { method ->
def name = method.getName()
FluentWrapper.metaClass."$name" = { Object[] varArgs ->
method.invoke(wrapped, name, varArgs)
return this
}
}
}
def methodMissing(String name, args) {
def method = delegate.getClass().getDeclaredMethods().find { it.match(name) }
if(method) {
method.invoke(delegate,name, args)
return FluentWrapper(delegate)
}
else throw new MissingMethodException(name, delegate, args)
}
}
Assuming example Java class:
class Person {
void setAge()
void setName()
}
I'd like to be able to execute the following piece of code:
def wrappedPerson = new FluentWrapper(new Person())
wrappedPerson.setAge().setName()
I'm using Groovy 1.6.7 for this.
This is all Groovy, and I'm using 1.8.6 (the current latest), but given this Person Class:
class Person {
int age
String name
public void setAge( int age ) { this.age = age }
public void setName( String name ) { this.name = name }
public String toString() { "$name $age" }
}
And this FluentWrapper class:
class FluentWrapper {
def delegate
FluentWrapper(wrapped) {
delegate = wrapped
}
def methodMissing(String name, args) {
def method = delegate.getClass().declaredMethods.find { it.name == name }
if(method) {
method.invoke( delegate, args )
return this
}
else throw new MissingMethodException(name, delegate, args)
}
}
Then, you should be able to do:
def wrappedPerson = new FluentWrapper(new Person())
Person person = wrappedPerson.setAge( 85 ).setName( 'tim' ).delegate
And person should have the age and name specified
I find #tim_yates' answer nice, but you couldn't access delegate methods' return values (something one usually likes doing, even for Builders in the case of build() :)
Moreover, if this wasn't intended for a Builder but for an object with a chainable interface (like that of jQuery wrapped objects in JS), it would be a serious issue.
So I'd put the wrapper like this:
class FluentWrapper {
def delegate
FluentWrapper(wrapped) {
delegate = wrapped
}
def methodMissing(String name, args) {
def method = delegate.getClass().declaredMethods.find { it.name == name }
if(method) {
def result = method.invoke(delegate, args)
return result != null ? result : this
}
else throw new MissingMethodException(name, delegate, args)
}
}
Note the elvis operator is unsuitable since a falsy value would never get returned.
Of course, it's up to the invoker to know wether a method is chainable or not, but that could be overcome with method annotations if neccesary.