With Java Annotations, can they accept a non-enum argument, like from a instance method? - annotations

With Java Annotations, is it possible to create a custom annoation that accepts a non-enum argument, like from a instance method?
For example, would this type of thing be possible to do?
#Builder(toBuilder = ENV_UTIL.getProperty("allowToBuilder"))
public class MyPojo {
//add fields here later
}
I am wondering because compiler wont let me do something like this with Lombok. So, does this mean there is a reason for this and it could never work, even on my own custom annotation?

Related

Pass a class name as string argument to create instance

Is there any possible way to pass a class name/path as String argument to call it in code in runtime?
Im working with some legacy code and i have no way to change it globally. Creating new integration to it suggest me to create new copy of class X, rename it, and pass new instance of Y i have created manually. My mind tells me to pass Y as some kind of argument and never copy X again.
I don't quite understand why you (think that) you need to do what you are trying to do (why copy class in the first place rather than just using it? why pass classname around instead of the class itself?), but, yeah, you can instantiate classes by (fully qualified) name using reflection.
First you get a handle to the class itself:
val clazz = Class.forName("foo.bar.X")
Then, if constructor does not need any arguments, you can just do
val instance = clazz.newInstance
If you need to pass arguments to constructor, it gets a bit more complicated.
val constructor = clazz.getConstructors().find { c =>
c.getParameters().map(_.getParameterizedType) == args.map(_.getClass)
}.getOrElse (throw new Exception("No suitable constructor found")
// or if you know for sure there will be only one constructor,
// could just do clazz.getConnstructors.headOption.getOrElse(...)
val instance = constructor.newInstance(args)
Note though, that the resulting instance is of type Object (AnyRef), so there isn't much you can actually do with it without casting to some interface type your class is known to implement.
Let me just say it again: it is very likely not the best way to achieve what you are actually trying to do. If you open another question and describe your actual problem (not the solution to it you are trying to implement), you might get more helpful answers.

Different field instances in class and parent/Call super constructor with method

I am trying to call the super constructor from a class using a method. The whole setup looks like this:
class Straight(hand: Hand) extends Combination(Straight.makeHandAceLowIfNeeded(hand), 5)
object Straight {
private def makeHandAceLowIfNeeded(hand: Hand): Hand = {
...
}
}
While this does compile, it has some rather odd runtime behaviour. While debugging, I noticed that the Straight instances have the "hand" property defined twice. Can somebody tell me what is going on, and what the proper way is to call the super constructor with different arguments?
In my use case, I want to call the super constructor with a modified hand in which I replaced a card compared to the original constructor argument.
Debugger screenshot with duplicate field:
.
It's a perfectly fine way to call the superclass constructor. These are two private fields and they don't conflict, though you can rename one of them to avoid confusion during debugging (or if you want to access the superclass' value from the subclass). However, the field should only be generated for a class parameter if it's used outside a constructor, and in your case it doesn't appear to be. Did you simplify the definition of Straight?

Java: help understanding the use of interfaces as a data type?

I am having trouble understanding with some of the code snippets about this part of the Java tutorial: http://docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html
public Object findLargest(Object object1, Object object2) {
Relatable obj1 = (Relatable)object1;
Relatable obj2 = (Relatable)object2;
if ((obj1).isLargerThan(obj2) > 0)
return object1;
else
return object2;
}
and:
public interface Relatable {
// this (object calling isLargerThan)
// and other must be instances of
// the same class returns 1, 0, -1
// if this is greater than,
// equal to, or less than other
public int isLargerThan(Relatable other);
}
In the first example, why am I downcasting Object types into Relatable types? What happens if the first method doesn't include the first two statements?
Let's say I wrote a Rectangle class that implements the Relatable interface and has the "findLargest" method. If I know that I'm comparing two Rectangle objects, why not just make the first method downcast the objects into Rectangles instead?
You cast the Objects into Relatable types because otherwise you cannot use the methods declared in the Relatable interface. Since Object does not have the isLargerThan method, you would get a compiler error without casting. Honestly, in my opinion the findLargest method as shown here was not very well designed; a better illustration of the purpose of Interfaces would be to ask for Relatable objects as the parameters like so:
public Object findLargest(Relatable object1, Relatable object2) {
//implementation not shown to save space
}
This way, the user must pass Relatable objects, but they can pass any object whose class implements Relatable (such as Rectangle)
"If I know that I'm comparing two Rectangle objects..."True, if you know that you are comparing two Rectangle objects, there is little use for an interface, but the purpose of interfaces is to allow you to create a generic "type" of object that can be used to define common features of several different classes.For example, what if you also had a Circle class and a Square class (both of which implemented Relatable)? In this case, you do not necessarily know the exact type of object you have, but you would know that it is Relatable, so it would be best to cast to type Relatable and use the isLargerThan method in a case like this.
Interfaces define a set of methods which every class which the interface implements has to implement. The downcast is necessary to get access to these methods.
You don't know if you are comparing rectangles with this interface. You could get any Relatble passed. This is one of the cases generics come in handy.
1.In the first example, why am I down casting Object types into Relatable types? What happens if the first method doesn't include the first two statements?
Answer
Every object has some basic functionality and you want a specific object write now. You are down casting your object into a "Relatable" so you can use the "isLargerThan" method(an object wont have it since it has only basic common stuff).
If you didn't down cast, you would not pass compilation.
2.Let's say I wrote a Rectangle class that implements the Relatable interface and has the "findLargest" method. If I know that I'm comparing two Rectangle objects, why not just make the first method downcast the objects into Rectangles instead?
Answer
Since you want to create something generic.
Lets say you have a Student and a Driver. Both of them are People. You can create an interface called IPeople and make both the Student and the driver implement it.
IPeople will have a method called "getAge()" that each of them will implement.
IPeople will have all the functionality that you need for "People". That's how you create cross object functionality under the "same hat".

C# allowing dynamic list of Generic Types

Is there a way to allow a user class with generics to be specified dynamically? That is, say I have a class hierarchy like this:
public interface IMyObject { }
Then I have a class like this:
public class MyObject<?> : IMyObject { }
I want to be able to use the object something like this:
MyObject<object> firstOrder;
MyObject<object, object> secondOrder;
MyObject<object, object, object> thirdOrder;
//And so on...
//MyObject<object, object, object> , ..., object> nthOrder;
I know for things like Func<>, Action<> or other delegates, I don't know that I've ever pushed the capacity of what these can do or whether their argument lists can so expansive.
Is there a way to do this in C#?
Thanks...
No, in C# you have to define each permutation separately. If you look at the examples you cited, Action<T> and Func<T>, you'll notice that the .NET framework provides a large number of explicit overloads (Action<T1, T2>, Action<T1, T2, T3>, etc.). But there's no way to make this open-ended; you have to define each one yourself.
No, you cannot have variadic type arguments. It might be cool, but it's not possible with the language as it stands. As for Func and Action, there are manual declarations for each number of type arguments. It's not something special that .NET just for those delegates.

Generic Wrapper Class possible?

On C# 3.0 and .NET 3.5, imagine there's an interface:
public interface INameable
{
string Name {get;}
}
and many immutable classes that implement the interface.
I would like to have a single extension method
public static T Rename<T>(this T obj) where T : INameable
{
...
}
that returns a wrapped instance of the original object with just the name changed and all other property reads and method calls routed to the original object.
How to get a generic wrapper class for this, without implementing it for all INameable implementing types? Do you think that's possible?
No, this isn't possible, unless T is constrained to be an interface or to be a class with all members virtual, and this constraint isn't possible to specify at compile time (though you could write a runtime check if you're happy with that approach).
The reason you cannot do it for arbitrary types is that if you take an object of type T then you must return an object that is assignable to T. If I pass an object that looks as follows...
public sealed class SomeClass : INameable
{
public string Name { get; }
public string Abc { get; }
}
...then there is no way you can create another type that is assignable to SomeClass. Not using Reflection.Emit or any other method, because the type is sealed.
However, if you're happy with the restrictions that I've mentioned then you could use something like the Castle DynamicProxy framework to create a type that proxies the passed in object and intercepts the calls to either forward or re-implement as appropriate.
Well, yes, it's possible, but it involves generating code in memory.
You can look at Reflection.Emit and here.
Note that it will involve a lot of code.
That is, if I assume I understand you correctly.
Here's what I think you're asking for:
SomeNameableObject a1 = new SomeNameableObject("ThisIsTheFirstName");
SomeNameableObject a2 = a1.Rename("ThisIsTheSecondName");
// a1 works, still has the name ThisIsTheFirstName
// a2 works, but everything is routed to a1,
// except for the name, which is ThisIsTheSecondName
Is that correct?