DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Proper Java Exception Handling
  • Solve the Java Spring Boot Enum
  • Async Programming Java: Part II
  • Abstract Factory Pattern In Java

Trending

  • Build a Serverless App Fast With Zipper: Write TypeScript, Offload Everything Else
  • Next.js vs. Gatsby: A Comprehensive Comparison
  • Mastering Persistence: Why the Persistence Layer Is Crucial for Modern Java Applications
  • Docker and Kubernetes Transforming Modern Deployment
  1. DZone
  2. Coding
  3. Java
  4. Java Generics Wildcard Capture - A Useful Thing to Know

Java Generics Wildcard Capture - A Useful Thing to Know

Shekhar Gulati user avatar by
Shekhar Gulati
·
Jan. 20, 11 · Interview
Like (1)
Save
Tweet
Share
49.92K Views

Join the DZone community and get the full member experience.

Join For Free

Recently, I was writing a piece of code where I need to write a copy factory for a class. A copy factory is a static factory that will construct a copy of the same type as that of the argument passed to the factory. The copy factory will copy the state of the argument object into the new object. This will make sure that the newly constructed object is equal to the old one. A copy constructor is similar to a copy factory with just one difference - a copy constructor can only exist in the class containing the constructor whereas copy factory can exist in any other class as well. For example,

// Copy Factory
public static Field getNewInstance(Field field)
// Copy Constructor
public Field Field(Field field)

I choose static copy factory because

  • I didn't have the source code for the class
  • With copy factory I can code to an interface instead of a class.

The class for which I wanted to write copy factory was similar to the one shown below :

public class Field<T> {
private String name;
private T value;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public T getValue() {
return value;
}

public void setValue(T value) {
this.value = value;
}

}

The first implementation of FieldUtils class that came to my mind was as shown below

public static Field<?> copy(Field<?> field) {
Field<?> objField = new Field<?>();//1
objField.setName(field.getName());//2
objField.setValue(field.getValue());//3
return objField;//4
}

The above code will not compile because of two compilation errors. The first compilation error is at line 1 because you can't create an instance of Field<?>.  Field<?> means Field<? extends Object> and when you have ? extends Something you can only get values out of it, you can't set values in it except null. For an object to be useful you should be able to do both, so the compiler does not allow you to create an object. The second compilation error will be at line number 3 and you will get a cryptic error message like this

The method setValue(capture#3-of ?) in the type Field<capture#3-of ?> is not applicable for the arguments (capture#4-of ?)

In simple terms this error message is saying that you are trying to set a wrong value in objField. But what if I had written the following method?

public static Field<?> copy(Field<?> field) {
field.setName(field.getName());
field.setValue(field.getValue());
return field;
}

Will the above code compile? No. You will again get a similar error message as mentioned above. To fix this error we will write a private helper method which will capture the wildcard and assign it to a Type variable. This technique is called Wildcard Capture. I have read this in the Java Generics and Collection book which is a must-read for understanding Java Generics. Wildcard Capture works by type inference.

public static Field<?> copy(Field<?> field) {
return copyHelper(field);
}

private static <T> Field<T> copyHelper(Field<T> field) {
Field<T> objField = new Field<T>();
objField.setName(field.getName());
objField.setValue(field.getValue());
return objField ;
}

Wildcard capture is very useful when you work with wildcards and knowing it will save a lot of your time.

Java (programming language) Factory (object-oriented programming) Error message

Opinions expressed by DZone contributors are their own.

Related

  • Proper Java Exception Handling
  • Solve the Java Spring Boot Enum
  • Async Programming Java: Part II
  • Abstract Factory Pattern In Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: