Comparator implementation with compare() methods - sorting

Here my class name is MyComparator2 but how can I use it here as a methods or object( am not sure ) MyComparator2() in another class name ComparaterDemo to define customized sorting . Can any one help to to make it clear regarding how one class can be used on another ??Thanks in advance
import java.util.Comparator;
import java.util.TreeSet;
public class ComparaterDemo {
public static void main(String[] args) {
TreeSet<Integer> treeSetCOllection = new TreeSet<Integer>(new MyComparator2());
treeSetCOllection.add(900);
treeSetCOllection.add(10);
treeSetCOllection.add(40);
treeSetCOllection.add(100);
treeSetCOllection.add(350);
System.out.println(treeSetCOllection);
}
}
class MyComparator2 implements Comparator{
public int compare(Object obj1, Object obj2){
Integer objectNumber1 = (Integer)obj1;
Integer objectNumber2 = (Integer)obj2;
if(objectNumber1<objectNumber2) return 1;
else if (objectNumber1>objectNumber2) return -1;
else return 0;
}
}

What's happening here is that you are constructing the TreeSet with the specified Comparator. How this works is, for each element added using the add() method, it will automatically sort the set. See here,

In order to make your class visible to other classes you need to specify its visibility. The three types of visibility in Java (I assume that's what you're using) are:
public
private
protected
They are defined as follows:
Public means that that class is visible to all classes regardless of where the file is located.
Private classes are classes inside of classes. For example, if MyComparator2 was defined inside of the ComparaterDemo class then ComparaterDemo could see it, but no other classes could.
Protected classes function the same as private classes except subclasses can also access them. So if MyComparator2 was defined inside of ComparaterDemo and SubComparaterDemo subclassed ComparaterDemo then SubComparaterDemo could access MyComparator2. In this example, no other classes except for ComparaterDemo and its subclasses could see it.
In your question, MyComparator2 is set to protected by default. If you change the line: "class MyComparator2 implements Comparator" to "public class MyComparator2 implements Comparator" you should have no more problems.
I hope this answers your question

Related

Using Lombok's #SuperBuilder concept on a class extended from a 3rd party library

I have a class hierarchy as below.
Child --> Parent --> SuperParent
Since the Child class has extended the Parent class I have to use Lombok's #SuperBuilder annotation instead of the #Builder. Also, as far as I know, all the superclasses need to have the #SuperBuilder annotation. But in my case, the SuperParent class comes from an external library, where I cannot add the #SuperBuilder annotation. I am getting the below compilation error.
The constructor SuperParent(DocumentUploadedResponseDto.DocumentUploadedResponseDtoBuilder<capture#1-of ?,capture#2-of ?>) is undefined.
Any solution or an alternative for this? Thank you.
It's a bit ugly, but it's possible. You have to insert a helper class into your inheritance chain between Parent and SuperParent; let's call it SuperParentBuilderEnabler. In this class, you have to manually implement all neccessary builder elements. Especially, you have to write all setter methods for the fields from SuperParent.
This will allow the Parent and Child classes to simply use a #SuperBuilder annotation without any further modifications.
I assume that SuperParent has an int superParentField field, just to demonstrate how you can write such a setter method in the builder class. Furthermore, I assume that this field can be set via constructor argument. Here is what you have to do:
public abstract class SuperParentBuilderEnabler extends SuperParent {
public static abstract class SuperParentBuilderEnablerBuilder<C extends SuperParentBuilderEnabler, B extends SuperParentBuilderEnablerBuilder<C, B>> {
private int superParentField;
public B superParentField(int superParentField) {
this.superParentField = superParentField;
return self();
}
protected abstract B self();
public abstract C build();
}
protected SuperParentBuilderEnabler(SuperParentBuilderEnablerBuilder<?, ?> b) {
super(b.superParentField);
}
}
Now let Parent extend SuperParentBuilderEnabler and you're done.
I'm sharing how I applied the accepted answer for RepresentationModel.
abstract class BaseTypeParent<T extends BaseTypeParent<T>>
extends RepresentationModel<T> {
protected abstract static class BaseTypeParentBuilder<
T extends BaseTypeParent<T>,
C extends BaseTypeParent<T>,
B extends BaseTypeParentBuilder<T, C, B>
> {
protected abstract B self();
public abstract C build();
}
protected BaseTypeParent(final BaseTypeParentBuilder<T, ?, ?> b) {
super();
}
}

final class and final member functions

Say I have the base class:
struct Base
{
virtual void foo();
};
and the derived class is final struct A final : public Base. Does it make sense to make the member functions final as well? I've seen in several places e.g.
struct A final : public Base {
void foo() final;
}
I am not sure it provides any value in this case as if the class itself is final I guess all the member functions are final by default as well. Am I missing something? Are there any guidelines?
In case a struct or a class (A in your case) is final, you cannot declare another one inheriting it. Therefore, there's no need to also declare any methods as final.
Maybe this is a convention in some places to be clear that this method also cannot be overridden (just as a "reminder" for the final of the struct).

CDI events and generics

I'm trying to send events and do this generically. I mean - create one abstract base DAO class with generic type and fire the event from its method. This should work for all descendants. This works if I define the exact type, but doesn't - if I use generics. What I mean:
AbstractDAO (with generics - doesn't fire the event):
public abstract class AbstractDAO<T extends Persistable> implements Serializable {
#Inject #PostSaveEvent Event<T> postSaveEvent;
public T saveOrUpdate(T object) throws DatabaseException {
T obj = em.merge(object);
postSaveEvent.fire(obj);
}
}
AbstractDAO (no generics, just simple class cast - fires the event):
public abstract class AbstractDAO<T extends Persistable> implements Serializable {
#Inject #PostSaveEvent Event<Polis> postSaveEvent;
public T saveOrUpdate(T object) throws DatabaseException {
T obj = em.merge(object);
postSaveEvent.fire((Polis)obj);
}
}
PolisDAO class, which extends AbstractDAO and defines the generic type:
#Stateless
#Named
#PolisType
public class PolisDAO extends AbstractDAO<Polis> {
// some methods (saveOrUpdate is not overriden!)
}
My observer class:
#Stateless
#Named
public class ProlongationService {
public void attachProlongationToPolisOnSave(#Observes #PostSaveEvent Polis polis) throws DatabaseException {
// ... DO smth with polis object. This is NOT called in the first case and called in the second
}
THis is very strange for me, as "fire()" method for CDI event should define the event type on runtime, not during compilation or deployment... When I debug, I see, that
postSaveEvent.fire(obj);
from the first sample operates exactly with Polis entity. But no event is fired nevertheless...
Upd. I tried the base generic class, but no luck:
#Inject #PostSaveEvent Event<Persistable> postSaveEvent;
Thanks.
This should, in theory, work, however in practice inspecting the type of generic objects at runtime with Java Reflection is, at times, impossible. This is due to type erasure. IIRC the type of the concrete sub class isn't erased, so it should be possible to reconnect this, but I guess the implementation isn't doing this right now.
File this as a bug in the http://issues.jboss.org/browse/WELD issue tracker (if you are using Weld), with the classes you provide as an example and we can try to fix it.
To work around, try injecting the event into the concrete subclass, and passing it as an argument, or using an accessor method, to get it into the abstract super class.

Spring: How to inject a value to static field?

With this class
#Component
public class Sample {
#Value("${my.name}")
public static String name;
}
If I try Sample.name, it is always 'null'. So I tried this.
public class Sample {
public static String name;
#PostConstruct
public void init(){
name = privateName;
}
#Value("${my.name}")
private String privateName;
public String getPrivateName() {
return privateName;
}
public void setPrivateName(String privateName) {
this.privateName = privateName;
}
}
This code works. Sample.name is set properly. Is this good way or not? If not, is there something more good way? And how to do it?
First of all, public static non-final fields are evil. Spring does not allow injecting to such fields for a reason.
Your workaround is valid, you don't even need getter/setter, private field is enough. On the other hand try this:
#Value("${my.name}")
public void setPrivateName(String privateName) {
Sample.name = privateName;
}
(works with #Autowired/#Resource). But to give you some constructive advice: Create a second class with private field and getter instead of public static field.
Soruce of this info is this: https://www.baeldung.com/spring-inject-static-field
Spring uses dependency injection to populate the specific value when it finds the #Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.
#RestController
//or if you want to declare some specific use of the properties file then use
//#Configuration
//#PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {
#Value("${name}")//not necessary
private String name;//not necessary
private static String NAME_STATIC;
#Value("${name}")
public void setNameStatic(String name){
PropertyController.NAME_STATIC = name;
}
}
This is my sample code for load static variable
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class OnelinkConfig {
public static int MODULE_CODE;
public static int DEFAULT_PAGE;
public static int DEFAULT_SIZE;
#Autowired
public void loadOnelinkConfig(#Value("${onelink.config.exception.module.code}") int code,
#Value("${onelink.config.default.page}") int page, #Value("${onelink.config.default.size}") int size) {
MODULE_CODE = code;
DEFAULT_PAGE = page;
DEFAULT_SIZE = size;
}
}
For those who want to use ApplicationContext in the main class of a Spring Boot application, you can just use the return value of SpringApplication.run.
Although workarounds may need to be implemented, one should try to avoid them in most scenarios if possible. Spring is great at handling dependency injection and treats most objects as Singletons. This means that Spring can handle the creation of objects for you, and the injection of these objects at runtime. When combining this with the fact that your Spring managed bean is likely a Singleton, the use of static methods and variables is largely unnecessary. You can simply autowire in an instance of the object you are looking for at the constructor level or variable level and reference the non-static version of the method or variable. This is ideal and behaves similarly to a static reference. Non static variables are basically static because you are only ever using one instance of the object in every part of the code and because of dependency injection you are never handling the instantiation of the object, just like with a static reference! Great! Now I'm sure there are instances where you need the work around (i.e. you aren't using dependency injection or class is not a singleton), but try to not use workarounds if possible. Also this is just my 2 cents. Someone may be able to offer 3. (:
public class InjectableClass{
#Value("${my.value}")
private String myString;
public String nonStaticMethod(){
return myString;
}
}
public class LogicClass{
private InjectableClass injectableClass;
#Autowire
public LogicClass(InjectableClass injectableClass){
this.injectableClass = injectableClass;
}
public void logicClassMethod(){
System.out.println("Hey! Here is the value I set on myString: " +
injectableClass.nonStaticMethod() + ". That was
basically like using a static method!");
}
}

Util class for accesing a Service in Spring 3

In Spring 3 it is not possible to set #Autowired in either static fields or methods, so since I want to declare an utility class such as:
public class SchoolYearServiceUtil {
private static SchoolYearService schoolYearService;
public static SchoolYear getSchoolYear(Long id) {
return schoolYearService.get(id);
}
}
to avoid having to inject the schoolYearService everywhere (jsp, command class...) in which I need it. In this case, I don't need an interface to be implemented by SchoolYearServiceUtil.
I don't want to have to initialize the object through code but getting the same instance as the Spring's one.
Which would be the best option to implement the getSchoolYear as a static method?
Thanks.
Would this be conceptually wrong?:
#Component
public class SchoolYearServiceUtil {
private static SchoolYearService schoolYearService;
#Autowired(required = true)
private SchoolYearServiceUtil(#Qualifier("schoolYearServiceImpl") SchoolYearService schoolYearService) {
SchoolYearServiceUtil.schoolYearService = schoolYearService;
}
public static SchoolYearService getSchoolYearService() {
return schoolYearService;
}
public static SchoolYear getSchoolYear(Long id) {
return getSchoolYearService().get(id);
}
}
I would have to make sure that only Spring calls once the constructor and the constructor is called nowhere else, that's why I declared the constructor as private.
I fully support skaffman's comment. You don't need static fields with DI. You just define a bean of scope singleton (default).
There is a way to obtain a bean statically, but you should be aware that it is not to be used in regular situations. (there are some valid applications). It is to use the WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)
You notice that you need to pass a ServletContext argument.

Resources